<html>
<head>
<title>Open Dynamics Engine</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css">
	h1.title {
		color:		#0000ff;
		font-weight:	bold;
		text-align:	center;
	}
	div.subtitle {
		color:		#0000ff;
		font-size:	smaller;
		padding-bottom:	10px;
	}
	div.author {
		color:		#000000;
		font-size:	smaller;
		font-style:	italic;
	}
	div.titledate {
		color:		#000000;
		font-size:	smaller;
		font-style:	italic;
		padding-bottom:	10px;
	}
	div.copyright {
		color:		#000000;
		font-size:	small;
	}
	h1.contents {
	}
	pre.code {
		background:	#c0ffff;
		color:		#0000ff;
		white-space:	pre;
	}
	span.c {
		font-family:	Courier, fixed, serif;
		white-space:	pre;
		font-size:	smaller;
	}
	span.arg {
		color:		#0000ff;
		font-family:	Courier, fixed, serif;
		font-size:	smaller;
	}
	a.func:link {
		color: #0000ff;
		font-family:	Courier, fixed, serif;
		font-size:	smaller;
	}
	a.func:visited {
		color: #0000ff;
		font-family:	Courier, fixed, serif;
		font-size:	smaller;
	}
	a.constref:link {
		color: #c00000;
		font-family:	Courier, fixed, serif;
		font-size:	smaller;
	}
	a.constref:visited {
		color: #c00000;
		font-family:	Courier, fixed, serif;
		font-size:	smaller;
	}
	pre.func1 {
		color:		#0000ff;
		white-space:	pre;
		font-family:	Courier, fixed, serif;
		margin-top:	5px;
		font-size:	smaller;
	}
	div.func2 {
		margin-left:	3em;
		margin-top:	5px;
		margin-bottom:	5px;
	}
	span.const {
		color:		#c00000;
		font-family:	Courier, fixed, serif;
		font-size:	smaller;
	}
	h1.section1 {
		font-weight:	bold;
		padding-top:	5px;
		border-top:	solid 2px black;
	}
	h2.section2 {
	}
	h3.section3 {
	}
	div.math {
		text-align:	center;
	}

	div.example {
		background:	#c0ffff;
		color:		#0000ff;
		width:		auto;
		font-weight:	bold;
		margin-left:	0em;
		margin-right:	0em;
		border-top:	solid 1px black;
		border-bottom:	solid 1px black;
		white-space:	pre;
		font-family:	Courier, fixed, serif;
		font-style:	normal;
		text-align:	left;
	}
</style>
</head>

<body bgcolor="#ffffff" link="#0000ff" alink="#0000ff" vlink="#0000ff">

<hr noshade size=2>
<h1 class="title">
	Open Dynamics Engine
	<div class="subtitle">v0.5 User Guide</div>
	<div class="author">Russell Smith</div>
	<div class="titledate">Saturday 29 May, 2004 </div>
	<div class="copyright">This document is Copyright &copy; 2001-2004 Russell Smith.</div>
</h1>
<hr noshade size=2>

<h1 class="contents">Contents</h1>
<ul><li><a href="#sec_1_0_0">1. Introduction</a>
<ul><li><a href="#sec_1_1_0">1.1. Features</a>
<li><a href="#sec_1_2_0">1.2. ODE's License</a>
<li><a href="#sec_1_3_0">1.3. The ODE Community</a>
</ul><li><a href="#sec_2_0_0">2. How to Install and Use ODE</a>
<ul><li><a href="#sec_2_1_0">2.1. Installing ODE</a>
<ul><li><a href="#sec_2_1_1">2.1.1. Building and Running ODE Tests on MacOS X</a>
</ul><li><a href="#sec_2_2_0">2.2. Using ODE</a>
</ul><li><a href="#sec_3_0_0">3. Concepts</a>
<ul><li><a href="#sec_3_1_0">3.1. Background</a>
<li><a href="#sec_3_2_0">3.2. Rigid bodies</a>
<ul><li><a href="#sec_3_2_1">3.2.1. Islands and Disabled Bodies</a>
</ul><li><a href="#sec_3_3_0">3.3. Integration</a>
<li><a href="#sec_3_4_0">3.4. Force accumulators</a>
<li><a href="#sec_3_5_0">3.5. Joints and constraints</a>
<li><a href="#sec_3_6_0">3.6. Joint groups</a>
<li><a href="#sec_3_7_0">3.7. Joint error and the error reduction parameter (ERP)</a>
<li><a href="#sec_3_8_0">3.8. Soft constraint and constraint force mixing (CFM)</a>
<ul><li><a href="#sec_3_8_1">3.8.1. Constraint Force Mixing (CFM)</a>
<li><a href="#sec_3_8_2">3.8.2. How To Use ERP and CFM</a>
</ul><li><a href="#sec_3_9_0">3.9. Collision handling</a>
<li><a href="#sec_3_10_0">3.10. Typical simulation code</a>
<li><a href="#sec_3_11_0">3.11. Physics model</a>
<ul><li><a href="#sec_3_11_1">3.11.1. Friction Approximation</a>
</ul></ul><li><a href="#sec_4_0_0">4. Data Types and Conventions</a>
<ul><li><a href="#sec_4_1_0">4.1. The basic data types</a>
<li><a href="#sec_4_2_0">4.2. Objects and IDs</a>
<li><a href="#sec_4_3_0">4.3. Argument conventions</a>
<li><a href="#sec_4_4_0">4.4. C versus C++</a>
<li><a href="#sec_4_5_0">4.5. Debugging</a>
</ul><li><a href="#sec_5_0_0">5. World</a>
<ul><li><a href="#sec_5_1_0">5.1. Stepping Functions</a>
<li><a href="#sec_5_2_0">5.2. Contact Parameters</a>
</ul><li><a href="#sec_6_0_0">6. Rigid Body Functions</a>
<ul><li><a href="#sec_6_1_0">6.1. Creating and Destroying Bodies</a>
<li><a href="#sec_6_2_0">6.2. Position and orientation</a>
<li><a href="#sec_6_3_0">6.3. Mass and force</a>
<li><a href="#sec_6_4_0">6.4. Utility</a>
<li><a href="#sec_6_5_0">6.5. Automatic Enabling and Disabling</a>
<li><a href="#sec_6_6_0">6.6. Miscellaneous Body Functions</a>
</ul><li><a href="#sec_7_0_0">7. Joint Types and Joint Functions</a>
<ul><li><a href="#sec_7_1_0">7.1. Creating and Destroying Joints</a>
<li><a href="#sec_7_2_0">7.2. Miscellaneous Joint Functions</a>
<li><a href="#sec_7_3_0">7.3. Joint parameter setting functions</a>
<ul><li><a href="#sec_7_3_1">7.3.1. Ball and Socket</a>
<li><a href="#sec_7_3_2">7.3.2. Hinge</a>
<li><a href="#sec_7_3_3">7.3.3. Slider</a>
<li><a href="#sec_7_3_4">7.3.4. Universal</a>
<li><a href="#sec_7_3_5">7.3.5. Hinge-2</a>
<li><a href="#sec_7_3_6">7.3.6. Fixed</a>
<li><a href="#sec_7_3_7">7.3.7. Contact</a>
<li><a href="#sec_7_3_8">7.3.8. Angular Motor</a>
</ul><li><a href="#sec_7_4_0">7.4. General</a>
<li><a href="#sec_7_5_0">7.5. Stop and motor parameters</a>
<ul><li><a href="#sec_7_5_1">7.5.1. Parameter Functions</a>
</ul><li><a href="#sec_7_6_0">7.6. Setting Joint Torques/Forces Directly</a>
</ul><li><a href="#sec_8_0_0">8. StepFast</a>
<ul><li><a href="#sec_8_1_0">8.1. When to use StepFast1</a>
<li><a href="#sec_8_2_0">8.2. When NOT to use StepFast1</a>
<li><a href="#sec_8_3_0">8.3. How it works</a>
<li><a href="#sec_8_4_0">8.4. Experimental Utilities included with StepFast1</a>
<li><a href="#sec_8_5_0">8.5. API</a>
</ul><li><a href="#sec_9_0_0">9. Support Functions</a>
<ul><li><a href="#sec_9_1_0">9.1. Rotation functions</a>
<li><a href="#sec_9_2_0">9.2. Mass functions</a>
<li><a href="#sec_9_3_0">9.3. Math functions</a>
<li><a href="#sec_9_4_0">9.4. Error and memory functions</a>
</ul><li><a href="#sec_10_0_0">10. Collision Detection</a>
<ul><li><a href="#sec_10_1_0">10.1. Contact points</a>
<li><a href="#sec_10_2_0">10.2. Geoms</a>
<li><a href="#sec_10_3_0">10.3. Spaces</a>
<li><a href="#sec_10_4_0">10.4. General geom functions</a>
<li><a href="#sec_10_5_0">10.5. Collision detection</a>
<ul><li><a href="#sec_10_5_1">10.5.1. Category and Collide Bitfields</a>
<li><a href="#sec_10_5_2">10.5.2. Collision Detection Functions</a>
</ul><li><a href="#sec_10_6_0">10.6. Space functions</a>
<li><a href="#sec_10_7_0">10.7. Geometry Classes</a>
<ul><li><a href="#sec_10_7_1">10.7.1. Sphere Class</a>
<li><a href="#sec_10_7_2">10.7.2. Box Class</a>
<li><a href="#sec_10_7_3">10.7.3. Plane Class</a>
<li><a href="#sec_10_7_4">10.7.4. Capped Cylinder Class</a>
<li><a href="#sec_10_7_5">10.7.5. Ray Class</a>
<li><a href="#sec_10_7_6">10.7.6. Triangle Mesh Class</a>
<li><a href="#sec_10_7_7">10.7.7. Geometry Transform Class</a>
</ul><li><a href="#sec_10_8_0">10.8. User defined classes</a>
<li><a href="#sec_10_9_0">10.9. Composite objects</a>
<li><a href="#sec_10_10_0">10.10. Utility functions</a>
<li><a href="#sec_10_11_0">10.11. Implementation notes</a>
<ul><li><a href="#sec_10_11_1">10.11.1. Large Environments</a>
<li><a href="#sec_10_11_2">10.11.2. Using a Different Collision Library</a>
</ul></ul><li><a href="#sec_11_0_0">11. How To Make Good Simulations</a>
<ul><li><a href="#sec_11_1_0">11.1. Integrator accuracy and stability</a>
<li><a href="#sec_11_2_0">11.2. Behavior may depend on step size</a>
<li><a href="#sec_11_3_0">11.3. Making things go faster</a>
<li><a href="#sec_11_4_0">11.4. Making things stable</a>
<li><a href="#sec_11_5_0">11.5. Using constraint force mixing (CFM)</a>
<li><a href="#sec_11_6_0">11.6. Avoiding singularities</a>
<li><a href="#sec_11_7_0">11.7. Other stuff</a>
</ul><li><a href="#sec_12_0_0">12. FAQ</a>
<ul><li><a href="#sec_12_1_0">12.1. How do I connect a body to the static environment with a joint?</a>
<li><a href="#sec_12_2_0">12.2. Does ODE need or use graphics library X ?</a>
<li><a href="#sec_12_3_0">12.3. Why do my rigid bodies bounce or penetrate on collision?
My restitution is zero!</a>
<li><a href="#sec_12_4_0">12.4. How can an immovable body be created?</a>
<li><a href="#sec_12_5_0">12.5. Why would you ever want to set ERP less than one?</a>
<li><a href="#sec_12_6_0">12.6. Is it advisable to set body velocities directly, instead of
applying a force or torque?</a>
<li><a href="#sec_12_7_0">12.7. Why, when I set a body's velocity directly, does it come up to speed
slower when joined to other bodies?</a>
<li><a href="#sec_12_8_0">12.8. Should I scale my units to be around 1.0 ?</a>
<li><a href="#sec_12_9_0">12.9. I've made a car, but the wheels don't stay on properly!</a>
<li><a href="#sec_12_10_0">12.10. How do I make ``one way'' collision interaction</a>
<li><a href="#sec_12_11_0">12.11. The Windows version of ODE crashes with large systems</a>
<li><a href="#sec_12_12_0">12.12. My simple rotating bodies are unstable!</a>
<li><a href="#sec_12_13_0">12.13. My rolling bodies (e.g. wheels) sometimes get stuck between geoms</a>
<ul><li><a href="#sec_12_13_1">12.13.1. The Problem</a>
<li><a href="#sec_12_13_2">12.13.2. The Solution</a>
</ul></ul><li><a href="#sec_13_0_0">13. Known Issues</a>
<li><a href="#sec_14_0_0">14. ODE Internals</a>
<ul><li><a href="#sec_14_1_0">14.1. Matrix storage conventions</a>
<li><a href="#sec_14_2_0">14.2. Internals FAQ</a>
<ul><li><a href="#sec_14_2_1">14.2.1. Why do some structures have a <span class=c>dx</span> prefix and some have a
<span class=c>d</span> prefix?</a>
<li><a href="#sec_14_2_2">14.2.2. Returned Vectors</a>
</ul></ul></ul>

<h1 class=section1><a name="sec_1_0_0">1. Introduction</a></h1>The Open Dynamics Engine (ODE) is a free, industrial quality library for
simulating articulated rigid body dynamics.
For example, it is good for simulating ground vehicles, legged creatures,
and moving objects in VR environments.
It is fast, flexible and robust, and it has built-in collision detection.
ODE is being developed by <a href="http://www.q12.org">Russell Smith</a>
with help from several
<a href="http://opende.sourceforge.net/community.html">contributors</a>.<p>If ``rigid body simulation'' does not make much sense to you, check out
<a href="http://opende.sourceforge.net/slides/slides.html">What is a Physics
SDK?</a>.<p>This is the user guide for ODE version 0.5.
Despite the low version number, ODE is reasonably mature and stable.<h2 class=section2><a name="sec_1_1_0">1.1. Features</a></h2>ODE is good for simulating <i>articulated</i> rigid body structures.
An articulated structure is created when rigid bodies of various shapes are
connected together with joints of various kinds.
Examples are ground vehicles (where the wheels are connected to the chassis),
legged creatures (where the legs are connected to the body), or stacks of
objects.<p>ODE is designed to be used in interactive or real-time simulation.
It is particularly good for simulating moving objects in changeable
virtual reality environments.
This is because it is fast, robust and stable, and the user has complete
freedom to change the structure of the system even while the simulation
is running.<p>ODE uses a highly stable integrator, so that the simulation errors should
not grow out of control.
The physical meaning of this is that the simulated system should not
"explode" for no reason (believe me, this happens a lot with other simulators
if you are not careful).
ODE emphasizes speed and stability over physical accuracy.<p>ODE has <i>hard</i> contacts. This means that a special non-penetration
constraint is used whenever two bodies collide.
The alternative, used in many other simulators, is to use virtual springs to
represent contacts.
This is difficult to do right and extremely error-prone.<p>ODE has a built-in collision detection system.
However you can ignore it and do your own collision detection if you want to.
The current collision primitives are sphere, box, capped cylinder, plane,
ray, and triangular mesh - more collision objects will come later.
ODE's collision system provides fast identification of potentially
intersecting objects, through the concept of ``spaces''.<p>Here are the features:
<ul>
<li>	Rigid bodies with arbitrary mass distribution.
<li>	Joint types: ball-and-socket, hinge, slider (prismatic),
	hinge-2, fixed, angular motor, universal.
<li>	Collision primitives: sphere, box, capped cylinder, plane,
	ray, and triangular mesh.
<li>	Collision spaces: Quad tree, hash space, and simple.
<li>	Simulation method: The equations of motion are derived from a
	Lagrange multiplier velocity based model due to Trinkle/Stewart and
	Anitescu/Potra.
<li>	A first order integrator is being used. It's fast, but not accurate
	enough for quantitative engineering yet. Higher order integrators
	will come later.
<li>	Choice of time stepping methods: either the standard ``big matrix''
	method or the newer iterative QuickStep method can be used.
<li>	Contact and friction model: This is based on the Dantzig LCP solver
	described by Baraff, although ODE implements a faster approximation
	to the Coloumb friction model.
<li>	Has a native C interface (even though ODE is mostly written in C++).
<li>	Has a C++ interface built on top of the C one.
<li>	Many unit tests, and more being written all the time.
<li>	Platform specific optimizations.
<li>	Other stuff I forgot to mention...
</ul><h2 class=section2><a name="sec_1_2_0">1.2. ODE's License</a></h2>ODE is Copyright &copy; 2001-2004 Russell L. Smith.
All rights reserved.<p>This library is free software; you can redistribute it and/or
modify it under the terms of EITHER:
<ol>
<li>	The <a href="http://www.opensource.org/licenses/lgpl-license.html">GNU
	Lesser General Public License</a> as published by the Free Software
	Foundation; either version 2.1 of the License, or (at your option)
	any later version. The text of the GNU Lesser General Public License
	is included with this library in the file <span class=c>LICENSE.TXT</span>.
<li>	The <a href="http://opende.sourceforge.net/ode-license.html">BSD-style
	license</a> that is included with this library in
	the file <span class=c>LICENSE-BSD.TXT</span>.
</ol>
This library is distributed in the hope that it will be useful,
but <i>WITHOUT ANY WARRANTY</i>; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files
<span class=c>LICENSE.TXT</span> and <span class=c>LICENSE-BSD.TXT</span> for more details.<h2 class=section2><a name="sec_1_3_0">1.3. The ODE Community</a></h2>Do you have questions or comments about ODE?
Think you can help? Please <a href="http://q12.org/mailman/listinfo/ode">write to
the ODE mailing list</a>.<h1 class=section1><a name="sec_2_0_0">2. How to Install and Use ODE</a></h1><h2 class=section2><a name="sec_2_1_0">2.1. Installing ODE</a></h2><b>Step 1:</b>
Unpack the ODE archive.<p><b>Steps 2-4 (alternate):</b>
If you're on windows and using MSVC, you can use the workspace and project
files in the VC6 subdirectory of the distribution.<p><b>Step 2:</b>
Get the GNU <span class=c>make</span> tool. Many Unix platforms come with this, although
sometimes it is called <span class=c>gmake</span>. A version of GNU make for windows is
available <a href="http://q12.org/ode/bin/make.exe">here</a>.<p><b>Step 3:</b>
Edit the settings in the file <span class=c>config/user-settings</span>.
The list of supported platforms is given in that file.<p><b>Step 4:</b>
Run GNU <span class=c>make</span> to configure and build ODE and the graphical test programs.
The configuration process creates the file <span class=c>include/ode/config.h</span>.<p><b>Step 5:</b>
To install the ODE library onto your system you should copy the <span class=c>lib/</span> and
<span class=c>include/</span> directories to a suitable place, e.g. on Unix:
<ul>
<li> <span class=c>include/ode/  --&gt; /usr/local/include/ode/</span>
<li> <span class=c>lib/libode.a --&gt; /usr/local/lib/libode.a</span>
</ul><h3 class=section3><a name="sec_2_1_1">2.1.1. Building and Running ODE Tests on MacOS X</a></h3>ODE uses XWindows and OpenGL to render the scene being simulated.
In order to build the example you will need to install Apple X11
server and the X11SDK (as well as the normal developer tools).<p>These are available from Apple. As of writing this can be found at:
<a href="http://www.apple.com/macosx/x11">http://www.apple.com/macosx/x11</a>.
NOTE: there is a tiny link at the bottom right of the page for the SDK<p>Once the software is installed follow the normal build instructions.<p>Since ODE uses X11 you need to run the X11 server (which you should
have installed, it's in the Applications Folder).<p>If you run the test app in the XTerm that the X11 server opens by
default then they should run fine. If however you run them from a MacOS X
Terminal then you need to define the environment variable DISPLAY. If
DISPLAY is not defined then you will get a message saying:
"cannot open X11 display".<p>For example to run the boxstack test you would type
<pre class=code>
    cd ode/test
    DISPLAY=:0.0 ./test_boxstack.exe</pre>
You can define this environment variable in your shell startup scripts
(for example in ~/.bashrc if you are using bash)<h2 class=section2><a name="sec_2_2_0">2.2. Using ODE</a></h2>The best way to understand how to use ODE is to look at the test/example
programs that come with it. Note the following things:
<ul>
<li>	Source files that use ODE only need to include a single header file:
<pre class=code>
 #include &lt;ode/ode.h&gt;</pre>
	The <span class=c>ode</span> directory in this statement is actually the
	<span class=c>include/ode</span> directory of the ODE distribution.
	This header file will include others in the <span class=c>ode</span> directory,
	so you need to set the include path of your compiler,
	e.g. in linux
<pre class=code>
 gcc -c -I /home/username/ode/include myprogram.cpp</pre><p><li>	When ODE is used with the <a class=func href="#func_dWorldStep">dWorldStep</a> function, heavy use is made
	of the stack for storing temporary values.
	For very large systems several megabytes of stack can be used.
	If you experience unexplained out-of-memory errors or data
	corruption, especially on Windows, try increasing the stack size, or
	switching to <a class=func href="#func_dWorldQuickStep">dWorldQuickStep</a>.
</ul><h1 class=section1><a name="sec_3_0_0">3. Concepts</a></h1><h2 class=section2><a name="sec_3_1_0">3.1. Background</a></h2>[Here is where I will write some background information about rigid body
dynamics and simulation.
But in the meantime, please refer to Baraff's excellent
<a href="http://www.cs.cmu.edu/~baraff/sigcourse/index.html">SIGGRAPH tutorial</a>].<h2 class=section2><a name="sec_3_2_0">3.2. Rigid bodies</a></h2>A rigid body has various properties from the point of view of the simulation.
Some properties change over time:
<ul>
<li>	Position vector (x,y,z) of the body's point of reference.
	Currently the point of reference must correspond to the body's
	center of mass.
<li>	Linear velocity of the point of reference, a vector (vx,vy,vz).
<li>	Orientation of a body, represented by a quaternion (qs,qx,qy,qz) or
	a 3x3 rotation matrix.
<li>	Angular velocity vector (wx,wy,wz) which describes how the orientation
	changes over time.<p></ul>
Other body properties are usually constant over time:
<ul>
<li>	Mass of the body.
<li>	Position of the center of mass with respect to the point of reference.
	In the current implementation the center of mass and the point of
	reference must coincide.
<li>	Inertia matrix. This is a 3x3 matrix that describes how the body's
	mass is distributed around the center of mass.
</ul>
Conceptually each body has an x-y-z coordinate frame embedded in it, that moves
and rotates with the body, as shown in figure 1.<p><center>
	<img border=1 src="pix/body.jpg"><br><br>
	<b>Figure 1</b>: The body coordinate frame.
	</center><p>The origin of this coordinate frame is the body's point of reference.
Some values in ODE (vectors, matrices etc) are relative to the body
coordinate frame, and others are relative to the global coordinate frame.<p>Note that the <i>shape</i> of a rigid body is not a dynamical property
(except insofar as it influences the various mass properties).
It is only <i>collision detection</i> that cares about the detailed shape of
the body.<h3 class=section3><a name="sec_3_2_1">3.2.1. Islands and Disabled Bodies</a></h3>Bodies are connected to each other with joints.
An ``island'' of bodies is a group that can not be pulled apart - in other
words each body is connected somehow to every other body in the island.<p>Each island in the world is treated separately when the simulation step is
taken.
This is useful to know: if there are <i>N</i> similar islands in the
simulation then the step computation time will be <i>O</i>(<i>N</i>).<p>Each body can be enabled or disabled.
Disabled bodies are effectively ``turned off'' and are not updated during a
simulation step.
Disabling bodies is an effective way to save computation time when it is known
that the bodies are motionless or otherwise irrelevant to the simulation.<p>If there are any enabled bodies in an island then every body in the island
will be enabled at the next simulation step.
Thus to effectively disable an island of bodies, <i>every</i> body in the
island must be disabled.
If a disabled island is touched by another enabled body then the entire
island will be enabled, as a contact joint will join the enabled body to
the island.<h2 class=section2><a name="sec_3_3_0">3.3. Integration</a></h2>The process of simulating the rigid body system through time is called
integration.
Each integration step advances the current time by a given step size,
adjusting the state of all the rigid bodies for the new time value.
There are two main issues to consider when working with any integrator:
<ul>
<li>	How accurate is it? That is, how closely does the behavior of the
	simulated system match what would happen in real life?
<li>	How stable is it? That is, will calculation errors ever cause
	completely non-physical behavior of the simulated system?
	(e.g. causing the system to "explode" for no reason).
</ul>
ODE's current integrator is very stable, but not particularly accurate
unless the step size is small.
For most uses of ODE this is not a problem -- ODE's behavior still looks
perfectly physical in almost all cases.
However ODE should not be used for quantitative engineering until this accuracy
issue has been addressed in a future release.<h2 class=section2><a name="sec_3_4_0">3.4. Force accumulators</a></h2>Between each integrator step the user can call functions to apply forces
to the rigid body.
These forces are added to "force accumulators" in the rigid body object.
When the next integrator step happens, the sum of all the applied forces
will be used to push the body around.
The forces accumulators are set to zero after each integrator step.<h2 class=section2><a name="sec_3_5_0">3.5. Joints and constraints</a></h2>In real life a joint is something like a hinge, that is used to connect two
objects.
In ODE a joint is very similar: It is a relationship that is enforced between
two bodies so that they can only have certain positions and orientations
relative to each other.
This relationship is called a <i>constraint</i> -- the words <i>joint</i> and
<i>constraint</i> are often used interchangeably.
Figure 2 shows three different constraint types.<p><center>
	<img border=1 src="pix/joints.jpg"><br><br>
	<b>Figure 2</b>: Three different constraint types.
	</center><p>The first is a ball and socket joint that constraints the ``ball'' of one
body to be in the same location as the ``socket'' of another body.
The second is a hinge joint that constraints the two parts of the
hinge to be in the same location and to line up along the hinge axle.
The third is a slider joint that constraints the ``piston'' and ``socket''
to line up, and additionally constraints the two bodies to have the same
orientation.<p>Each time the integrator takes a step all the joints are allowed to apply
<i>constraint forces</i> to the bodies they affect.
These forces are calculated such that the bodies move in such a way to
preserve all the joint relationships.<p>Each joint has a number of parameters controlling its geometry.
An example is the position of the ball-and-socket point for a ball-and-socket
joint.
The functions to set joint parameters all take <i>global</i> coordinates,
not body-relative coordinates.
A consequence of this is that the rigid bodies that a joint connects must be
positioned correctly <i>before</i> the joint is attached.<h2 class=section2><a name="sec_3_6_0">3.6. Joint groups</a></h2>A joint group is a special container that holds joints in a world.
Joints can be added to a group, and then when those joints are no
longer needed the entire group of joints can be very quickly destroyed
with one function call.
However, individual joints in a group can not be destroyed before the entire
group is emptied.<p>This is most useful with contact joints, which are added and remove from
the world in groups every time step.<h2 class=section2><a name="sec_3_7_0">3.7. Joint error and the error reduction parameter (ERP)</a></h2>When a joint attaches two bodies, those bodies are required to have certain
positions and orientations relative to each other.
However, it is possible for the bodies to be in positions where the joint
constraints are not met.
This ``joint error'' can happen in two ways:
<ol>
<li>	If the user sets the position/orientation of one body without correctly
	setting the position/orientation of the other body.
<li>	During the simulation, errors can creep in that result in the bodies
	drifting away from their required positions.
</ol>
Figure 3 shows an example of error in a ball and socket
joint (where the ball and socket do not line up).<p><center>
	<img border=1 src="pix/ball-and-socket-bad.jpg"><br><br>
	<b>Figure 3</b>: An example of error in a ball and socket joint.
	</center><p>There is a mechanism to reduce joint error: during each simulation step each
joint applies a special force to bring its bodies back into correct alignment.
This force is controlled by the <i>error reduction parameter</i> (ERP),
which has a value between 0 and 1.<p>The ERP specifies what proportion of the joint error will be
fixed during the next simulation step.
If ERP=0 then no correcting force is applied and the bodies will eventually
drift apart as the simulation proceeds.
If ERP=1 then the simulation will attempt to fix all joint error during the
next time step.
However, setting ERP=1 is not recommended, as the joint error will not be
completely fixed due to various internal approximations.
A value of ERP=0.1 to 0.8 is recommended (0.2 is the default).<p>A global ERP value can be set that affects most joints in the simulation.
However some joints have local ERP values that control various aspects of
the joint.<h2 class=section2><a name="sec_3_8_0">3.8. Soft constraint and constraint force mixing (CFM)</a></h2>Most constraints are by nature ``hard''.
This means that the constraints represent conditions that are never violated.
For example, the ball must always be in the socket, and the two parts of the
hinge must always be lined up.
In practice constraints can be violated by unintentional introduction of
errors into the system, but the error reduction parameter can be set to
correct these errors.<p>Not all constraints are hard.
Some ``soft'' constraints are designed to be violated.
For example, the contact constraint that prevents colliding objects from
penetrating is hard by default, so it acts as though the colliding surfaces
are made of steel.
But it can be made into a soft constraint to simulate softer materials,
thereby allowing some natural penetration of the two objects when they are
forced together.<p>There are two parameters that control the distinction between hard and soft
constraints. The first is the error reduction parameter (ERP) that has already
been introduced.
The second is the constraint force mixing (CFM) value, that is described below.<h3 class=section3><a name="sec_3_8_1">3.8.1. Constraint Force Mixing (CFM)</a></h3>What follows is a somewhat technical description of the meaning of CFM.
If you just want to know how it is used in practice then skip to the next
section.<p>Traditionally the constraint equation for every joint has the form<p><div class=math><i>J</i> * <i>v</i> = <i>c</i></div><p>where <i>v</i> is a velocity vector for the bodies involved, <i>J</i> is a
``Jacobian'' matrix with one row for every degree of freedom the joint
removes from the system, and <i>c</i> is a right hand side vector.
At the next time step, a vector <i>lambda</i> is calculated (of the same
size as <i>c</i>) such that the forces applied to the bodies to preserve the
joint constraint are<p><div class=math><i>force</i> = <i>J</i><sup><i>T</i></sup> *  <i>lambda</i> </div><p>ODE adds a new twist.
ODE's constraint equation has the form<p><div class=math><i>J</i> * <i>v</i> = <i>c</i> + <i>CFM</i> *  <i>lambda</i> </div><p>where <i>CFM</i> is a square diagonal matrix.
<i>CFM</i> mixes the resulting constraint force in with the constraint that
produces it.
A nonzero (positive) value of <i>CFM</i> allows the original constraint
equation to be violated by an amount proportional to CFM times the restoring
force  <i>lambda</i>  that is needed to enforce the constraint.
Solving for  <i>lambda</i>  gives<p><div class=math>(<i>J</i> <i>M</i><sup>-1</sup> <i>J</i><sup><i>T</i></sup> + <i>CFM</i>/<i>h</i>)  <i>lambda</i>  = <i>c</i>/<i>h</i></div><p>Thus <i>CFM</i> simply adds to the diagonal of the original system matrix.
Using a positive value of <i>CFM</i> has the additional benefit of taking the
system away from any singularity and thus improving the factorizer accuracy.<h3 class=section3><a name="sec_3_8_2">3.8.2. How To Use ERP and CFM</a></h3>ERP and CFM can be independently set in many joints. They can be set in
contact joints, in joint limits and various other places, to control the
spongyness and springyness of the joint (or joint limit).<p>If CFM is set to zero, the constraint will be hard.
If CFM is set to a positive value, it will be possible to violate the
constraint by ``pushing on it'' (for example, for contact constraints by
forcing the two contacting objects together).
In other words the constraint will be soft, and the softness will increase
as CFM increases.
What is actually happening here is that the constraint is allowed to be
violated by an amount proportional to CFM times the restoring force that is
needed to enforce the constraint.
Note that setting CFM to a negative value can have undesirable bad effects,
such as instability. Don't do it.<p>By adjusting the values of ERP and CFM, you can achieve various effects.
For example you can simulate springy constraints, where the two bodies
oscillate as though connected by springs.
Or you can simulate more spongy constraints, without the oscillation.
In fact, ERP and CFM can be selected to have the same effect as any
desired spring and damper constants.
If you have a spring constant <i>k</i><sub><i>p</i></sub> and damping constant <i>k</i><sub><i>d</i></sub>,
then the corresponding ODE constants are:<p><div class=math><i>ERP</i> = <i>h</i> <i>k</i><sub><i>p</i></sub> / (<i>h</i> <i>k</i><sub><i>p</i></sub> + <i>k</i><sub><i>d</i></sub>)</div>
	<div class=math><i>CFM</i> = 1 / (<i>h</i> <i>k</i><sub><i>p</i></sub> + <i>k</i><sub><i>d</i></sub>)</div><p>where <i>h</i> is the stepsize.
These values will give the same effect as a spring-and-damper system simulated
with implicit first order integration.<p>Increasing CFM, especially the global CFM, can reduce the numerical errors
in the simulation. If the system is near-singular, then this can markedly
increase stability.
In fact, if the system is mis-behaving, one of the first things to try is
to increase the global CFM.<h2 class=section2><a name="sec_3_9_0">3.9. Collision handling</a></h2>[There is a lot that needs to be written about collision handling.]<p>Collisions between bodies or between bodies and the static environment are
handled as follows:
<ol>
<li>	Before each simulation step, the user calls collision detection
	functions to determine what is touching what.
	These functions return a list of contact points.
	Each contact point specifies a position in space, a surface normal
	vector, and a penetration depth.<p><li>	A special contact joint is created for each contact point.
	The contact joint is given extra information about the contact,
	for example the friction present at the contact surface, how bouncy
	or soft it is, and various other properties.<p><li>	The contact joints are put in a joint "group", which allows them to be
	added to and removed from the system very quickly.
	The simulation speed goes down as the number of contacts goes up,
	so various strategies can be used to limit the number of contact
	points.<p><li>	A simulation step is taken.<p><li>	All contact joints are removed from the system.
</ol>
Note that the built-in collision functions do not have to be used -
other collision detection libraries can be used as long as they provide
the right kinds of contact point information.<h2 class=section2><a name="sec_3_10_0">3.10. Typical simulation code</a></h2>A typical simulation will proceed like this:
<ol>
<li>	Create a dynamics world.
<li>	Create bodies in the dynamics world.
<li>	Set the state (position etc) of all bodies.
<li>	Create joints in the dynamics world.
<li>	Attach the joints to the bodies.
<li>	Set the parameters of all joints.
<li>	Create a collision world and collision geometry objects, as
	necessary.
<li>	Create a joint group to hold the contact joints.
<li>	Loop: <ol>
	<li>	Apply forces to the bodies as necessary.
	<li>	Adjust the joint parameters as necessary.
	<li>	Call collision detection.
	<li>	Create a contact joint for every collision point, and put it
		in the contact joint group.
	<li>	Take a simulation step.
	<li>	Remove all joints in the contact joint group.
	</ol>
<li>	Destroy the dynamics and collision worlds.
</ol><h2 class=section2><a name="sec_3_11_0">3.11. Physics model</a></h2>The various methods and approximations that are used in ODE are discussed
here.<h3 class=section3><a name="sec_3_11_1">3.11.1. Friction Approximation</a></h3>[We really need more pictures here.]<p>The Coulomb friction model is a simple, but effective way to model friction
at contact points.
It is a simple relationship between the normal and tangential forces present
at a contact point (see the contact joint section for a description of these
forces). The rule is:<p><div class=math>| <i>f</i><sub><i>T</i></sub> | &lt;=  <i>mu</i>  * | <i>f</i><sub><i>N</i></sub> |</div><p>where <i>f</i><sub><i>N</i></sub> and <i>f</i><sub><i>T</i></sub> are the normal and tangential force vectors
respectively, and  <i>mu</i>  is the friction coefficient (typically a number
around 1.0).
This equation defines a "friction cone" - imagine a cone with <i>f</i><sub><i>N</i></sub> as the
axis and the contact point as the vertex.
If the total friction force vector is within the cone then the contact is in
"sticking mode", and the friction force is enough to prevent the contacting
surfaces from moving with respect to each other.
If the force vector is on the surface of the cone then the contact is in
"sliding mode", and the friction force is typically not large enough to
prevent the contacting surfaces from sliding.
The parameter  <i>mu</i>  thus specifies the maximum ratio of tangential to normal
force.<p>ODE's friction models are approximations to the friction cone, for reasons of
efficiency. There are currently two approximations to chose from:
<ol>
<li>	The meaning of  <i>mu</i>  is changed so that it specifies the
	maximum friction (tangential) force that can be present at a contact,
	in either of the tangential friction directions.
	This is rather non physical because it is independent of the normal
	force, but it can be useful and it is the computationally cheapest
	option. Note that in this case  <i>mu</i>  is a force limit an must be
	chosen appropriate to the simulation.
<li>	The friction cone is approximated by a friction pyramid aligned with
	the first and second friction directions [I really need a picture
	here].
	A further approximation is made: first ODE computes the normal forces
	assuming that all the contacts are frictionless. Then it computes the
	maximum limits <i>f</i><sub><i>m</i></sub> for the friction (tangential) forces from<p><div class=math><i>f</i><sub><i>m</i></sub> =  <i>mu</i>  * | <i>f</i><sub><i>N</i></sub> |</div><p>and then proceeds to solve for the entire system with these fixed
	limits (in a manner similar to approximation 1 above).
	This differs from a true friction pyramid in that the "effective"
	 <i>mu</i>  is not quite fixed.
	This approximation is easier to use as  <i>mu</i>  is a unit-less ratio
	the same as the normal Coloumb friction coefficient, and thus can be
	set to a constant value around 1.0 without regard for the specific
	simulation.
</ol><h1 class=section1><a name="sec_4_0_0">4. Data Types and Conventions</a></h1><h2 class=section2><a name="sec_4_1_0">4.1. The basic data types</a></h2>The ODE library can be built to use either single or double precision floating
point numbers.
Single precision is faster and uses less memory, but the simulation will
have more numerical error that can result in visible problems.
You will get less accuracy and stability with single precision.<p>[must describe what factors influence accuracy and stability].<p>The floating point data type is <span class=c>dReal</span>.
Other commonly used types are <span class=c>dVector3</span>, <span class=c>dVector4</span>, <span class=c>dMatrix3</span>,
<span class=c>dMatrix4</span>, <span class=c>dQuaternion</span>.<h2 class=section2><a name="sec_4_2_0">4.2. Objects and IDs</a></h2>There are various kinds of object that can be created:
<ul>
<li>	dWorld - a dynamics world.
<li>	dSpace - a collision space.
<li>	dBody - a rigid body.
<li>	dGeom - geometry (for collision).
<li>	dJoint - a joint
<li>	dJointGroup - a group of joints.
</ul>
Functions that deal with these objects take and return object IDs.
The object ID types are <span class=c>dWorldID</span>, <span class=c>dBodyID</span>, etc.<h2 class=section2><a name="sec_4_3_0">4.3. Argument conventions</a></h2>All 3-vectors (x,y,z) supplied to ``set'' functions are given as individual
x,y,z arguments.<p>All 3-vector result arguments to get() function are pointers to arrays of
<span class=c>dReal</span>.<p>Larger vectors are always supplied and returned as pointers to arrays of
<span class=c>dReal</span>.<p>All coordinates are in the global frame except where otherwise specified.<h2 class=section2><a name="sec_4_4_0">4.4. C versus C++</a></h2>The ODE library is written in C++, but its public interface is made of simple
C functions, not classes. Why is this?
<ul>
<li>	Using a C interface only is simpler - the features of C++ features do
	not help much for ODE.
<li>	It prevents C++ mangling and runtime-support problems across multiple
	compilers.
<li>	The user doesn't have to be familiar with C++ quirks to use ODE.
</ul><h2 class=section2><a name="sec_4_5_0">4.5. Debugging</a></h2>The ODE library can be compiled in "debugging" or "release" mode.
Debugging mode is slower, but function arguments are checked and many
run-time tests are done to ensure internal consistency.
Release mode is faster, but no checking is done.<h1 class=section1><a name="sec_5_0_0">5. World</a></h1>The world object is a container for rigid bodies and joints.
Objects in different worlds can not interact, for example rigid bodies from
two different worlds can not collide.<p>All the objects in a world exist at the same point in time, thus one reason
to use separate worlds is to simulate systems at different rates.<p>Most applications will only need one world.<p><a name="func_dWorldCreate">
<pre class=func1>
dWorldID dWorldCreate();
</pre><div class=func2>
Create a new, empty world and return its ID number.
</div><p><a name="func_dWorldDestroy">
<pre class=func1>
void dWorldDestroy (dWorldID);
</pre><div class=func2>
Destroy a world and everything in it. This includes all bodies, and all
joints that are not part of a joint group.
Joints that are part of a joint group will be deactivated, and can be
destroyed by calling, for example, <a class=func href="#func_dJointGroupEmpty">dJointGroupEmpty</a>.
</div><p><a name="func_dWorldSetGravity">
<a name="func_dWorldGetGravity">
<pre class=func1>
void dWorldSetGravity (dWorldID, dReal x, dReal y, dReal z);
void dWorldGetGravity (dWorldID, dVector3 gravity);
</pre><div class=func2>
Set and get the world's global gravity vector. The units are m/s/s, so Earth's
gravity vector would be (0,0,-9.81), assuming that +z is up.
The default is no gravity, i.e. (0,0,0).
</div><p><a name="func_dWorldSetERP">
<a name="func_dWorldGetERP">
<pre class=func1>
void dWorldSetERP (dWorldID, dReal erp);
dReal dWorldGetERP (dWorldID);
</pre><div class=func2>
Set and get the global ERP value, that controls how much error correction is
performed in each time step.
Typical values are in the range 0.1--0.8.
The default is 0.2.
</div><p><a name="func_dWorldSetCFM">
<a name="func_dWorldGetCFM">
<pre class=func1>
void dWorldSetCFM (dWorldID, dReal cfm);
dReal dWorldGetCFM (dWorldID);
</pre><div class=func2>
Set and get the global CFM (constraint force mixing) value.
Typical values are in the range 10<sup>-9</sup> -- 1.
The default is 10<sup>-5</sup> if single precision is being used, or 10<sup>-10</sup> if double
precision is being used.
</div><p><a name="func_dWorldSetAutoDisableFlag">
<a name="func_dWorldGetAutoDisableFlag">
<a name="func_dWorldSetAutoDisableLinearThreshold">
<a name="func_dWorldGetAutoDisableLinearThreshold">
<a name="func_dWorldSetAutoDisableAngularThreshold">
<a name="func_dWorldGetAutoDisableAngularThreshold">
<a name="func_dWorldSetAutoDisableSteps">
<a name="func_dWorldGetAutoDisableSteps">
<a name="func_dWorldSetAutoDisableTime">
<a name="func_dWorldGetAutoDisableTime">
<pre class=func1>
void  dWorldSetAutoDisableFlag (dWorldID, int do_auto_disable);
int   dWorldGetAutoDisableFlag (dWorldID);
void  dWorldSetAutoDisableLinearThreshold (dWorldID, dReal linear_threshold);
dReal dWorldGetAutoDisableLinearThreshold (dWorldID);
void  dWorldSetAutoDisableAngularThreshold (dWorldID, dReal angular_threshold);
dReal dWorldGetAutoDisableAngularThreshold (dWorldID);
void  dWorldSetAutoDisableSteps (dWorldID, int steps);
int   dWorldGetAutoDisableSteps (dWorldID);
void  dWorldSetAutoDisableTime (dWorldID, dReal time);
dReal dWorldGetAutoDisableTime (dWorldID);
</pre><div class=func2>
Set and get the default auto-disable parameters for newly created bodies.
See <a href="#sec_6_5_0">section 6.5</a> for a description of the auto-disable feature.
The default parameters are:
<ul>
<li>	AutoDisableFlag = disabled
<li>	AutoDisableLinearThreshold = 0.01
<li>	AutoDisableAngularThreshold = 0.01
<li>	AutoDisableSteps = 10
<li>	AutoDisableTime = 0
</ul>
</div><p><a name="func_dWorldImpulseToForce">
<pre class=func1>
void dWorldImpulseToForce (dWorldID, dReal stepsize,
			   dReal ix, dReal iy, dReal iz, dVector3 force);
</pre><div class=func2>
If you want to apply a linear or angular impulse to a rigid body,
instead of a force or a torque, then you can use this function to convert
the desired impulse into a force/torque vector before calling the
<span class=c>dBodyAdd...</span> function.<p>This function is given the desired impulse as (<span class=arg>ix</span>,<span class=arg>iy</span>,<span class=arg>iz</span>)
and puts the force vector in <span class=arg>force</span>.
The current algorithm simply scales the impulse by 1/<span class=arg>stepsize</span>,
where <span class=arg>stepsize</span> is the step size for the <i>next</i> step that will
be taken.<p>This function is given a <span class=c>dWorldID</span> because, in the future, the force
computation may depend on integrator parameters that are set as
properties of the world.
</div><p><a name="func_dCloseODE">
<pre class=func1>
void dCloseODE();
</pre><div class=func2>
This deallocates some extra memory used by ODE that can not be deallocated
using the normal destroy functions, e.g. <a class=func href="#func_dWorldDestroy">dWorldDestroy</a>.
You can use this function at the end of your application to prevent
memory leak checkers from complaining about ODE.
</div><h2 class=section2><a name="sec_5_1_0">5.1. Stepping Functions</a></h2><a name="func_dWorldStep">
<pre class=func1>
void dWorldStep (dWorldID, dReal stepsize);
</pre><div class=func2>
Step the world.
This uses a "big matrix" method that takes time on the order of <i>m</i><sup>3</sup>
and memory on the order of <i>m</i><sup>2</sup>, where <i>m</i> is the total number of constraint rows.<p>For large systems this will use a lot of memory and can be very slow,
but this is currently the most accurate method.
</div><p><a name="func_dWorldQuickStep">
<pre class=func1>
void dWorldQuickStep (dWorldID, dReal stepsize);
</pre><div class=func2>
Step the world.
This uses an iterative method that takes time on the order of <i>m</i>*<i>N</i>
and memory on the order of <i>m</i>, where <i>m</i> is the total number of constraint rows
and <i>N</i> is the number of iterations.<p>For large systems this is a lot faster than <a class=func href="#func_dWorldStep">dWorldStep</a>,
but it is less accurate.<p>QuickStep is great for stacks of objects especially when the auto-disable feature
is used as well.
However, it has poor accuracy for near-singular systems.
Near-singular systems can occur when using high-friction contacts, motors,
or certain articulated structures. For example, a robot with multiple legs
sitting on the ground may be near-singular.<p>There are ways to help overcome QuickStep's inaccuracy problems:
<ul>
<li>	Increase CFM.
<li>	Reduce the number of contacts in your system (e.g. use the minimum
	number of contacts for the feet of a robot or creature).
<li>	Don't use excessive friction in the contacts.
<li>	Use contact slip if appropriate
<li>	Avoid kinematic loops (however, kinematic loops are inevitable in
	legged creatures).
<li>	Don't use excessive motor strength.
<li>	Use force-based motors instead of velocity-based motors.
</ul>
Increasing the number of QuickStep iterations may help a little bit, but
it is not going to help much if your system is really near singular.<p></div><p><a name="func_dWorldSetQuickStepNumIterations">
<a name="func_dWorldGetQuickStepNumIterations">
<pre class=func1>
void dWorldSetQuickStepNumIterations (dWorldID, int num);
int dWorldGetQuickStepNumIterations (dWorldID);
</pre><div class=func2>
Set and get the number of iterations that the QuickStep method performs per step.
More iterations will give a more accurate solution, but will take longer to compute.
The default is 20 iterations.
</div><h2 class=section2><a name="sec_5_2_0">5.2. Contact Parameters</a></h2><a name="func_dWorldSetContactMaxCorrectingVel">
<a name="func_dWorldGetContactMaxCorrectingVel">
<pre class=func1>
void dWorldSetContactMaxCorrectingVel (dWorldID, dReal vel);
dReal dWorldGetContactMaxCorrectingVel (dWorldID);
</pre><div class=func2>
Set and get the maximum correcting velocity that contacts are allowed to generate.
The default value is infinity (i.e. no limit).
Reducing this value can help prevent "popping" of deeply embedded objects.
</div><p><a name="func_dWorldSetContactSurfaceLayer">
<a name="func_dWorldGetContactSurfaceLayer">
<pre class=func1>
void dWorldSetContactSurfaceLayer (dWorldID, dReal depth);
dReal dWorldGetContactSurfaceLayer (dWorldID);
</pre><div class=func2>
Set and get the depth of the surface layer around all geometry objects.
Contacts are allowed to sink into the surface layer up to the given
depth before coming to rest.
The default value is zero.
Increasing this to some small value (e.g. 0.001) can help prevent jittering problems
due to contacts being repeatedly made and broken.
</div><h1 class=section1><a name="sec_6_0_0">6. Rigid Body Functions</a></h1><h2 class=section2><a name="sec_6_1_0">6.1. Creating and Destroying Bodies</a></h2><a name="func_dBodyCreate">
<pre class=func1>
dBodyID dBodyCreate (dWorldID);
</pre><div class=func2>
Create a body in the given world with default mass parameters at
position (0,0,0).
Return its ID.
</div><p><a name="func_dBodyDestroy">
<pre class=func1>
void dBodyDestroy (dBodyID);
</pre><div class=func2>
Destroy a body.
All joints that are attached to this body will be put into limbo
(i.e. unattached and not affecting the simulation, but they will NOT be
deleted).
</div><h2 class=section2><a name="sec_6_2_0">6.2. Position and orientation</a></h2><a name="func_dBodySetPosition">
<a name="func_dBodySetRotation">
<a name="func_dBodySetQuaternion">
<a name="func_dBodySetLinearVel">
<a name="func_dBodySetAngularVel">
<a name="func_dBodyGetPosition">
<a name="func_dBodyGetRotation">
<a name="func_dBodyGetQuaternion">
<a name="func_dBodyGetLinearVel">
<a name="func_dBodyGetAngularVel">
<pre class=func1>
void dBodySetPosition   (dBodyID, dReal x, dReal y, dReal z);
void dBodySetRotation   (dBodyID, const dMatrix3 R);
void dBodySetQuaternion (dBodyID, const dQuaternion q);
void dBodySetLinearVel  (dBodyID, dReal x, dReal y, dReal z);
void dBodySetAngularVel (dBodyID, dReal x, dReal y, dReal z);
const dReal * dBodyGetPosition   (dBodyID);
const dReal * dBodyGetRotation   (dBodyID);
const dReal * dBodyGetQuaternion (dBodyID);
const dReal * dBodyGetLinearVel  (dBodyID);
const dReal * dBodyGetAngularVel (dBodyID);
</pre><div class=func2>
These functions set and get the position, rotation, linear and angular
velocity of the body.
After setting a group of bodies, the outcome of the simulation is undefined
if the new configuration is inconsistent with the joints/constraints that are
present.
When getting, the returned values are pointers to internal data structures,
so the vectors are valid until any changes are made to the rigid body system
structure.<p>Hmmm. <span class=c>dBodyGetRotation</span> returns a 4x3 rotation matrix.
</div><h2 class=section2><a name="sec_6_3_0">6.3. Mass and force</a></h2><a name="func_dBodySetMass">
<a name="func_dBodyGetMass">
<pre class=func1>
void dBodySetMass (dBodyID, const dMass *mass);
void dBodyGetMass (dBodyID, dMass *mass);
</pre><div class=func2>
Set/get the mass of the body (see the mass functions).
</div><p><a name="func_dBodyAddForce">
<a name="func_dBodyAddTorque">
<a name="func_dBodyAddRelForce">
<a name="func_dBodyAddRelTorque">
<a name="func_dBodyAddForceAtPos">
<a name="func_dBodyAddForceAtRelPos">
<a name="func_dBodyAddRelForceAtPos">
<a name="func_dBodyAddRelForceAtRelPos">
<pre class=func1>
void dBodyAddForce            (dBodyID, dReal fx, dReal fy, dReal fz);
void dBodyAddTorque           (dBodyID, dReal fx, dReal fy, dReal fz);
void dBodyAddRelForce         (dBodyID, dReal fx, dReal fy, dReal fz);
void dBodyAddRelTorque        (dBodyID, dReal fx, dReal fy, dReal fz);
void dBodyAddForceAtPos       (dBodyID, dReal fx, dReal fy, dReal fz,
                                        dReal px, dReal py, dReal pz);
void dBodyAddForceAtRelPos    (dBodyID, dReal fx, dReal fy, dReal fz,
                                        dReal px, dReal py, dReal pz);
void dBodyAddRelForceAtPos    (dBodyID, dReal fx, dReal fy, dReal fz,
                                        dReal px, dReal py, dReal pz);
void dBodyAddRelForceAtRelPos (dBodyID, dReal fx, dReal fy, dReal fz,
                                        dReal px, dReal py, dReal pz);
</pre><div class=func2>
Add forces to bodies (absolute or relative coordinates).
The forces are accumulated on to each body, and the accumulators are zeroed
after each time step.<p>The ...<span class=c>RelForce</span> and ...<span class=c>RelTorque</span> functions take force vectors that are
relative to the body's own frame of reference.<p>The ...<span class=c>ForceAtPos</span> and ...<span class=c>ForceAtRelPos</span> functions take an extra
position vector (in global or body-relative coordinates respectively)
that specifies the point at which the force is applied.
All other functions apply the force at the center of mass.
</div><p><a name="func_dBodyGetForce">
<a name="func_dBodyGetTorque">
<pre class=func1>
const dReal * dBodyGetForce  (dBodyID);
const dReal * dBodyGetTorque (dBodyID);
</pre><div class=func2>
Return the current accumulated force and torque vector.
The returned pointers point to an array of 3 <span class=c>dReal</span>s.
The returned values are pointers to internal data structures, so the vectors
are only valid until any changes are made to the rigid body system.
</div><p><a name="func_dBodySetForce">
<a name="func_dBodySetTorque">
<pre class=func1>
void dBodySetForce  (dBodyID b, dReal x, dReal y, dReal z);
void dBodySetTorque (dBodyID b, dReal x, dReal y, dReal z);
</pre><div class=func2>
Set the body force and torque accumulation vectors.
This is mostly useful to zero the force and torque for deactivated bodies
before they are reactivated, in the case where the force-adding functions
were called on them while they were deactivated.
</div><h2 class=section2><a name="sec_6_4_0">6.4. Utility</a></h2><a name="func_dBodyGetRelPointPos">
<a name="func_dBodyGetRelPointVel">
<a name="func_dBodyGetPointVel">
<pre class=func1>
void dBodyGetRelPointPos (dBodyID, dReal px, dReal py, dReal pz,
                          dVector3 result);
void dBodyGetRelPointVel (dBodyID, dReal px, dReal py, dReal pz,
                          dVector3 result);
void dBodyGetPointVel    (dBodyID, dReal px, dReal py, dReal pz,
                          dVector3 result);
</pre><div class=func2>
Utility functions that take a point on a body (<span class=arg>px</span>,<span class=arg>py</span>,<span class=arg>pz</span>) and
return that point's position or velocity in global coordinates
(in <span class=arg>result</span>).
The <span class=c>dBodyGetRelPointXXX</span> functions are given the point in body
relative coordinates, and the <span class=c>dBodyGetPointVel</span> function is given
the point in global coordinates.
</div><p><a name="func_dBodyGetPosRelPoint">
<pre class=func1>
void dBodyGetPosRelPoint (dBodyID, dReal px, dReal py, dReal pz,
                       	  dVector3 result);
</pre><div class=func2>
This is the inverse of <a class=func href="#func_dBodyGetRelPointPos">dBodyGetRelPointPos</a>.
It takes a point in global coordinates (<span class=arg>x</span>,<span class=arg>y</span>,<span class=arg>z</span>) and returns
the point's position in body-relative coordinates (<span class=arg>result</span>).
</div><p><a name="func_dBodyVectorToWorld">
<a name="func_dBodyVectorFromWorld">
<pre class=func1>
void dBodyVectorToWorld   (dBodyID, dReal px, dReal py, dReal pz,
                           dVector3 result);
void dBodyVectorFromWorld (dBodyID, dReal px, dReal py, dReal pz,
                           dVector3 result);
</pre><div class=func2>
Given a vector expressed in the body (or world) coordinate system
(<span class=arg>x</span>,<span class=arg>y</span>,<span class=arg>z</span>), rotate it to the world (or body) coordinate system
(<span class=arg>result</span>).
</div><h2 class=section2><a name="sec_6_5_0">6.5. Automatic Enabling and Disabling</a></h2>Every body can be enabled or disabled.
Enabled bodies participate in the simulation, while
disabled bodies are turned off and do not get updated during a simulation step.
New bodies are always created in the enabled state.<p>A disabled body that is connected through a joint to an enabled body will
be automatically re-enabled at the next simulation step.<p>Disabled bodies do not consume CPU time, therefore to speed up the simulation
bodies should be disabled when they come to rest.
This can be done automatically with the auto-disable feature.<p>If a body has its auto-disable flag turned on, it will automatically disable itself
when
<ol>
<li>	It has been idle for a given number of simulation steps.
<li>	It has also been idle for a given amount of simulation time.
</ol>
A body is considered to be idle when the magnitudes of both its linear velocity
and angular velocity are below given thresholds.<p>Thus, every body has five auto-disable parameters: an enabled flag, a idle step count,
an idle time, and linear/angular velocity thresholds.
Newly created bodies get these parameters from world.<p>The following functions set and get the enable/disable parameters of a body.<p><a name="func_dBodyEnable">
<a name="func_dBodyDisable">
<pre class=func1>
void dBodyEnable (dBodyID);
void dBodyDisable (dBodyID);
</pre><div class=func2>
Manually enable and disable a body.
Note that a disabled body that is connected through a joint to an enabled body will
be automatically re-enabled at the next simulation step.
</div><p><a name="func_dBodyIsEnabled">
<pre class=func1>
int dBodyIsEnabled (dBodyID);
</pre><div class=func2>
Return 1 if a body is currently enabled or 0 if it is disabled.
</div><p><a name="func_dBodySetAutoDisableFlag">
<a name="func_dBodyGetAutoDisableFlag">
<pre class=func1>
void  dBodySetAutoDisableFlag (dBodyID, int do_auto_disable);
int   dBodyGetAutoDisableFlag (dBodyID);
</pre><div class=func2>
Set and get the auto-disable flag of a body.
If the <span class=arg>do_auto_disable</span> is nonzero the body will be automatically disabled when
it has been idle for long enough.
</div><p><a name="func_dBodySetAutoDisableLinearThreshold">
<a name="func_dBodyGetAutoDisableLinearThreshold">
<pre class=func1>
void  dBodySetAutoDisableLinearThreshold (dBodyID, dReal linear_threshold);
dReal dBodyGetAutoDisableLinearThreshold (dBodyID);
</pre><div class=func2>
Set and get a body's linear velocity threshold for automatic disabling.
The body's linear velocity magnitude must be less than this threshold for it
to be considered idle.
Set the threshold to <span class=c>dInfinity</span> to prevent the linear velocity from being considered.
</div><p><a name="func_dBodySetAutoDisableAngularThreshold">
<a name="func_dBodyGetAutoDisableAngularThreshold">
<pre class=func1>
void  dBodySetAutoDisableAngularThreshold (dBodyID, dReal angular_threshold);
dReal dBodyGetAutoDisableAngularThreshold (dBodyID);
</pre><div class=func2>
Set and get a body's angular velocity threshold for automatic disabling.
The body's linear angular magnitude must be less than this threshold for it
to be considered idle.
Set the threshold to <span class=c>dInfinity</span> to prevent the angular velocity from being considered.
</div><p><a name="func_dBodySetAutoDisableSteps">
<a name="func_dBodyGetAutoDisableSteps">
<pre class=func1>
void  dBodySetAutoDisableSteps (dBodyID, int steps);
int   dBodyGetAutoDisableSteps (dBodyID);
</pre><div class=func2>
Set and get the number of simulation steps that a body must be idle before it
is automatically disabled.
Set this to zero to disable consideration of the number of steps.
</div><p><a name="func_dBodySetAutoDisableTime">
<a name="func_dBodyGetAutoDisableTime">
<pre class=func1>
void  dBodySetAutoDisableTime (dBodyID, dReal time);
dReal dBodyGetAutoDisableTime (dBodyID);
</pre><div class=func2>
Set and get the amount of simulation time that a body must be idle before it
is automatically disabled.
Set this to zero to disable consideration of the amount of simulation time.
</div><p><a name="func_dBodySetAutoDisableDefaults">
<pre class=func1>
void  dBodySetAutoDisableDefaults (dBodyID);
</pre><div class=func2>
Set the auto-disable parameters of the body to the default parameters that have
been set on the world.
</div><h2 class=section2><a name="sec_6_6_0">6.6. Miscellaneous Body Functions</a></h2><a name="func_dBodySetData">
<a name="func_dBodyGetData">
<pre class=func1>
void  dBodySetData (dBodyID, void *data);
void *dBodyGetData (dBodyID);
</pre><div class=func2>
Get and set the body's user-data pointer.
</div><p><a name="func_dBodySetFiniteRotationMode">
<pre class=func1>
void dBodySetFiniteRotationMode (dBodyID, int mode);
</pre><div class=func2>
This function controls the way a body's orientation is updated at each time
step. The <span class=arg>mode</span> argument can be:
<ul>
<li>	0: An ``infinitesimal'' orientation update is used.
	This is fast to compute, but it can occasionally cause inaccuracies
	for bodies that are rotating at high speed, especially when those
	bodies are joined to other bodies.
	This is the default for every new body that is created.
<li>	1: A ``finite'' orientation update is used.
	This is more costly to compute, but will be more accurate for high
	speed rotations.
	Note however that high speed rotations can result in many types of
	error in a simulation, and this mode will only fix one of those
	sources of error.
</ul>
</div><p><a name="func_dBodyGetFiniteRotationMode">
<pre class=func1>
int dBodyGetFiniteRotationMode (dBodyID);
</pre><div class=func2>
Return the current finite rotation mode of a body (0 or 1).
</div><p><a name="func_dBodySetFiniteRotationAxis">
<pre class=func1>
void dBodySetFiniteRotationAxis (dBodyID, dReal x, dReal y, dReal z);
</pre><div class=func2>
This sets the finite rotation axis for a body.
This is axis only has meaning when the finite rotation mode is set
(see <a class=func href="#func_dBodySetFiniteRotationMode">dBodySetFiniteRotationMode</a>).<p>If this axis is zero (0,0,0), full finite rotations are performed on the body.<p>If this axis is nonzero, the body is rotated by performing a partial finite
rotation along the axis direction followed by an infinitesimal rotation along
an orthogonal direction.<p>This can be useful to alleviate certain sources of error caused by quickly
spinning bodies. For example, if a car wheel is rotating at high speed
you can call this function with the wheel's hinge axis as the argument to
try and improve its behavior.
</div><p><a name="func_dBodyGetFiniteRotationAxis">
<pre class=func1>
void dBodyGetFiniteRotationAxis (dBodyID, dVector3 result);
</pre><div class=func2>
Return the current finite rotation axis of a body.
</div><p><a name="func_dBodyGetNumJoints">
<pre class=func1>
int dBodyGetNumJoints (dBodyID b);
</pre><div class=func2>
Return the number of joints that are attached to this body.
</div><p><a name="func_dBodyGetJoint">
<pre class=func1>
dJointID dBodyGetJoint (dBodyID, int index);
</pre><div class=func2>
Return a joint attached to this body, given by <span class=arg>index</span>.
Valid indexes are 0 to <i>n</i>-1 where <i>n</i> is the value returned by
<a class=func href="#func_dBodyGetNumJoints">dBodyGetNumJoints</a>.
</div><p><a name="func_dBodySetGravityMode">
<a name="func_dBodyGetGravityMode">
<pre class=func1>
void dBodySetGravityMode (dBodyID b, int mode);
int dBodyGetGravityMode (dBodyID b);
</pre><div class=func2>
Set/get whether the body is influenced by the world's gravity or not.
If <span class=arg>mode</span> is nonzero it is, if <span class=arg>mode</span> is zero, it isn't.
Newly created bodies are always influenced by the world's gravity.
</div><h1 class=section1><a name="sec_7_0_0">7. Joint Types and Joint Functions</a></h1><h2 class=section2><a name="sec_7_1_0">7.1. Creating and Destroying Joints</a></h2><a name="func_dJointCreateBall">
<a name="func_dJointCreateHinge">
<a name="func_dJointCreateSlider">
<a name="func_dJointCreateContact">
<a name="func_dJointCreateUniversal">
<a name="func_dJointCreateHinge2">
<a name="func_dJointCreateFixed">
<a name="func_dJointCreateAMotor">
<pre class=func1>
dJointID dJointCreateBall (dWorldID, dJointGroupID);
dJointID dJointCreateHinge (dWorldID, dJointGroupID);
dJointID dJointCreateSlider (dWorldID, dJointGroupID);
dJointID dJointCreateContact (dWorldID, dJointGroupID,
                              const dContact *);
dJointID dJointCreateUniversal (dWorldID, dJointGroupID);
dJointID dJointCreateHinge2 (dWorldID, dJointGroupID);
dJointID dJointCreateFixed (dWorldID, dJointGroupID);
dJointID dJointCreateAMotor (dWorldID, dJointGroupID);
</pre><div class=func2>
Create a new joint of a given type.
The joint is initially in "limbo" (i.e. it has no effect on the simulation)
because it does not connect to any bodies.
The joint group ID is 0 to allocate the joint normally.
If it is nonzero the joint is allocated in the given joint group.
The contact joint will be initialized with the given <span class=c>dContact</span>
structure.
</div><p><a name="func_dJointDestroy">
<pre class=func1>
void dJointDestroy (dJointID);
</pre><div class=func2>
Destroy a joint, disconnecting it from its attached bodies and removing
it from the world.
However, if the joint is a member of a group then this function has no
effect - to destroy that joint the group must be emptied or destroyed.
</div><p><a name="func_dJointGroupCreate">
<pre class=func1>
dJointGroupID dJointGroupCreate (int max_size);
</pre><div class=func2>
Create a joint group.
The <span class=arg>max_size</span> argument is now unused and should be set to 0.
It is kept for backwards compatibility.
</div><p><a name="func_dJointGroupDestroy">
<pre class=func1>
void dJointGroupDestroy (dJointGroupID);
</pre><div class=func2>
Destroy a joint group. All joints in the joint group will be destroyed.
</div><p><a name="func_dJointGroupEmpty">
<pre class=func1>
void dJointGroupEmpty (dJointGroupID);
</pre><div class=func2>
Empty a joint group. All joints in the joint group will be destroyed,
but the joint group itself will not be destroyed.
</div><h2 class=section2><a name="sec_7_2_0">7.2. Miscellaneous Joint Functions</a></h2><a name="func_dJointAttach">
<pre class=func1>
void dJointAttach (dJointID, dBodyID body1, dBodyID body2);
</pre><div class=func2>
Attach the joint to some new bodies.
If the joint is already attached, it will be detached from the old bodies
first.
To attach this joint to only one body, set body1 or body2 to zero - a zero
body refers to the static environment.
Setting both bodies to zero puts the joint into "limbo", i.e. it will
have no effect on the simulation.<p>Some joints, like hinge-2 need to be attached to two bodies to work.
</div><p><a name="func_dJointSetData">
<a name="func_dJointGetData">
<pre class=func1>
void dJointSetData (dJointID, void *data);
void *dJointGetData (dJointID);
</pre><div class=func2>
Get and set the joint's user-data pointer.
</div><p><a name="func_dJointGetType">
<pre class=func1>
int dJointGetType (dJointID);
</pre><div class=func2>
Get the joint's type. One of the following constants will be returned:<p><center><table border=1 cellspacing=0 cellpadding=6 bgcolor=#ffffc0><tr valign="top"><td><a name="const_dJointTypeBall"><span class=const>dJointTypeBall</span></td><td>A ball-and-socket joint.</td></tr><tr valign="top"><td><a name="const_dJointTypeHinge"><span class=const>dJointTypeHinge</span></td><td>A hinge joint.</td></tr><tr valign="top"><td><a name="const_dJointTypeSlider"><span class=const>dJointTypeSlider</span></td><td>A slider joint.</td></tr><tr valign="top"><td><a name="const_dJointTypeContact"><span class=const>dJointTypeContact</span></td><td>A contact joint.</td></tr><tr valign="top"><td><a name="const_dJointTypeUniversal"><span class=const>dJointTypeUniversal</span></td><td>A universal joint.</td></tr><tr valign="top"><td><a name="const_dJointTypeHinge2"><span class=const>dJointTypeHinge2</span></td><td>A hinge-2 joint.</td></tr><tr valign="top"><td><a name="const_dJointTypeFixed"><span class=const>dJointTypeFixed</span></td><td>A fixed joint.</td></tr><tr valign="top"><td><a name="const_dJointTypeAMotor"><span class=const>dJointTypeAMotor</span></td><td>An angular motor joint.</td></tr></table></center>
</div><p><a name="func_dJointGetBody">
<pre class=func1>
dBodyID dJointGetBody (dJointID, int index);
</pre><div class=func2>
Return the bodies that this joint connects.
If <span class=arg>index</span> is 0 the ``first'' body will be returned, corresponding to the <span class=c>body1</span>
argument of <a class=func href="#func_dJointAttach">dJointAttach</a>.
If <span class=arg>index</span> is 1 the ``second'' body will be returned, corresponding to the <span class=c>body2</span>
argument of <a class=func href="#func_dJointAttach">dJointAttach</a>.<p>If one of these returned body IDs is zero, the joint connects the other body
to the static environment.
If both body IDs are zero, the joint is in ``limbo'' and has no effect on
the simulation.
</div><p><a name="func_dJointSetFeedback">
<a name="func_dJointGetFeedback">
<pre class=func1>
void dJointSetFeedback (dJointID, dJointFeedback *);
dJointFeedback *dJointGetFeedback (dJointID);
</pre><div class=func2>
During the world time step, the forces that are applied by each joint are
computed. These forces are added directly to the joined bodies, and the user
normally has no way of telling which joint contributed how much force.<p>If this information is desired then the user can allocate a <span class=c>dJointFeedback</span>
structure and pass its pointer to the <span class=c>dJointSetFeedback()</span> function.
The feedback information structure is defined as follows:<p><pre class=code>
typedef struct dJointFeedback {
  dVector3 f1;       // force that joint applies to body 1
  dVector3 t1;       // torque that joint applies to body 1
  dVector3 f2;       // force that joint applies to body 2
  dVector3 t2;       // torque that joint applies to body 2
} dJointFeedback;</pre><p>During the time step any feedback structures that are attached to joints will
be filled in with the joint's force and torque information.
The <span class=c>dJointGetFeedback()</span> function returns the current feedback
structure pointer, or 0 if none is used (this is the default).
<span class=c>dJointSetFeedback()</span> can be passed 0 to disable feedback for that joint.<p>Now for some API design notes.
It might seem strange to require that users perform the allocation of
these structures. Why not just store the data statically in each
joint? The reason is that not all users will use the feedback
information, and even when it is used not all joints will need it.
It will waste memory to store it statically, especially as this
structure could grow to store a lot of extra information in the
future.<p>Why not have ODE allocate the structure itself, at the user's request?
The reason is that contact joints (which are created and destroyed
every time step) would require a lot of time to be spent in memory
allocation if feedback is required. Letting the user do the allocation
means that a better allocation strategy can be provided, e.g simply
allocating them out of a fixed array.<p>The alternative to this API is to have a joint-force callback. This
would work of course, but it has a few problems. First, callbacks tend
to pollute APIs and sometimes require the user to go through unnatural
contortions to get the data to the right place. Second, this would
expose ODE to being changed in the middle of a step (which
would have bad consequences), and there would have to be some kind of
guard against this or a debugging check for it - which would complicate
things.
</div><p><a name="func_dAreConnected">
<pre class=func1>
int dAreConnected (dBodyID, dBodyID);
</pre><div class=func2>
Utility function: return 1 if the two bodies are connected together by
a joint, otherwise return 0.
</div><p><a name="func_dAreConnectedExcluding">
<pre class=func1>
int dAreConnectedExcluding (dBodyID, dBodyID, int joint_type);
</pre><div class=func2>
Utility function: return 1 if the two bodies are connected together by
a joint that does not have type <span class=arg>joint_type</span>, otherwise return 0.
<span class=arg>joint_type</span> is a <span class=c>dJointTypeXXX</span> constant.
This is useful for deciding whether to add contact joints between two bodies:
if they are already connected by non-contact joints then it may not be
appropriate to add contacts, however it is okay to add more contact between-
bodies that already have contacts.
</div><h2 class=section2><a name="sec_7_3_0">7.3. Joint parameter setting functions</a></h2><h3 class=section3><a name="sec_7_3_1">7.3.1. Ball and Socket</a></h3>A ball and socket joint is shown in figure 4.<p><center>
	<img border=1 src="pix/ball-and-socket.jpg"><br><br>
	<b>Figure 4</b>: A ball and socket joint.
	</center><p><a name="func_dJointSetBallAnchor">
<pre class=func1>
void dJointSetBallAnchor (dJointID, dReal x, dReal y, dReal z);
</pre><div class=func2>
Set the joint anchor point.  The joint will try to keep this point on each body
together.  The input is specified in world coordinates.
</div><p><a name="func_dJointGetBallAnchor">
<pre class=func1>
void dJointGetBallAnchor (dJointID, dVector3 result);
</pre><div class=func2>
Get the joint anchor point, in world coordinates.  This returns the point on
body 1.  If the joint is perfectly satisfied, this will be the same as the
point on body 2.
</div><p><a name="func_dJointGetBallAnchor2">
<pre class=func1>
void dJointGetBallAnchor2 (dJointID, dVector3 result);
</pre><div class=func2>
Get the joint anchor point, in world coordinates.  This returns the point on
body 2.  You can think of a ball and socket joint as trying to keep the result
of dJointGetBallAnchor() and dJointGetBallAnchor2() the same.  If the joint is
perfectly satisfied, this function will return the same value
as <a class=func href="#func_dJointGetBallAnchor">dJointGetBallAnchor</a> to within roundoff errors.  <a class=func href="#func_dJointGetBallAnchor2">dJointGetBallAnchor2</a>
can be used, along with <a class=func href="#func_dJointGetBallAnchor">dJointGetBallAnchor</a>, to see how far the joint has come apart.
</div><h3 class=section3><a name="sec_7_3_2">7.3.2. Hinge</a></h3>A hinge joint is shown in figure 5.<p><center>
	<img border=1 src="pix/hinge.jpg"><br><br>
	<b>Figure 5</b>: A hinge joint.
	</center><p><a name="func_dJointSetHingeAnchor">
<a name="func_dJointSetHingeAxis">
<pre class=func1>
void dJointSetHingeAnchor (dJointID, dReal x, dReal y, dReal z);
void dJointSetHingeAxis (dJointID, dReal x, dReal y, dReal z);
</pre><div class=func2>
Set hinge anchor and axis parameters.
</div><p><a name="func_dJointGetHingeAnchor">
<pre class=func1>
void dJointGetHingeAnchor (dJointID, dVector3 result);
</pre><div class=func2>
Get the joint anchor point, in world coordinates.  This returns the point on
body 1.  If the joint is perfectly satisfied, this will be the same as the
point on body 2.
</div><p><a name="func_dJointGetHingeAnchor2">
<pre class=func1>
void dJointGetHingeAnchor2 (dJointID, dVector3 result);
</pre><div class=func2>
Get the joint anchor point, in world coordinates.  This returns the point on
body 2.  If the joint is perfectly satisfied, this will return the same value
as <a class=func href="#func_dJointGetHingeAnchor">dJointGetHingeAnchor</a>.  If not, this value will be slightly different.
This can be used, for example, to see how far the joint has come apart.
</div><p><a name="func_dJointGetHingeAxis">
<pre class=func1>
void dJointGetHingeAxis (dJointID, dVector3 result);
</pre><div class=func2>
Get hinge axis parameter.
</div><p><a name="func_dJointGetHingeAngle">
<a name="func_dJointGetHingeAngleRate">
<pre class=func1>
dReal dJointGetHingeAngle (dJointID);
dReal dJointGetHingeAngleRate (dJointID);
</pre><div class=func2>
Get the hinge angle and the time derivative of this value.
The angle is measured between the two bodies, or between the body and
the static environment.
The angle will be between -pi..pi.<p>When the hinge anchor or axis is set, the current position of the attached
bodies is examined and that position will be the zero angle.
</div><h3 class=section3><a name="sec_7_3_3">7.3.3. Slider</a></h3>A slider joint is shown in figure 6.<p><center>
	<img border=1 src="pix/slider.jpg"><br><br>
	<b>Figure 6</b>: A slider joint.
	</center><p><a name="func_dJointSetSliderAxis">
<pre class=func1>
void dJointSetSliderAxis (dJointID, dReal x, dReal y, dReal z);
</pre><div class=func2>
Set the slider axis parameter.
</div><p><a name="func_dJointGetSliderAxis">
<pre class=func1>
void dJointGetSliderAxis (dJointID, dVector3 result);
</pre><div class=func2>
Get the slider axis parameter.
</div><p><a name="func_dJointGetSliderPosition">
<a name="func_dJointGetSliderPositionRate">
<pre class=func1>
dReal dJointGetSliderPosition (dJointID);
dReal dJointGetSliderPositionRate (dJointID);
</pre><div class=func2>
Get the slider linear position (i.e. the slider's ``extension'') and the time
derivative of this value.<p>When the axis is set, the current position of the attached bodies is
examined and that position will be the zero position.
</div><h3 class=section3><a name="sec_7_3_4">7.3.4. Universal</a></h3>A universal joint is shown in figure 7.<p><center>
	<img border=1 src="pix/universal.jpg"><br><br>
	<b>Figure 7</b>: A universal joint.
	</center><p>A universal joint is like a ball and socket joint that constrains an
extra degree of rotational freedom. Given axis 1 on body 1, and axis 2
on body 2 that is perpendicular to axis 1, it keeps them
perpendicular. In other words, rotation of the two bodies about the
direction perpendicular to the two axes will be equal.<p>In the picture, the two bodies are joined together by a cross. Axis 1
is attached to body 1, and axis 2 is attached to body 2. The cross
keeps these axes at 90 degrees, so if you grab body 1 and twist it,
body 2 will twist as well.<p>A Universal joint is equivalent to a hinge-2 joint where the hinge-2's
axes are perpendicular to each other, and with a perfectly
rigid connection in place of the suspension.<p>Universal joints show up in cars, where the engine causes a shaft, the
drive shaft, to rotate along its own axis. At some point you'd like to
change the direction of the shaft. The problem is, if you just bend
the shaft, then the part after the bend won't rotate about its own
axis. So if you cut it at the bend location and insert a universal
joint, you can use the constraint to force the second shaft to rotate
about the same angle as the first shaft.<p>Another use of this joint is to attach the arms of a simple virtual
creature to its body. Imagine a person holding their arms straight
out. You may want the arm to be able to move up and down, and forward
and back, but not to rotate about its own axis.<p>Here are the universal joint functions:<p><a name="func_dJointSetUniversalAnchor">
<a name="func_dJointSetUniversalAxis1">
<a name="func_dJointSetUniversalAxis2">
<pre class=func1>
void dJointSetUniversalAnchor (dJointID, dReal x, dReal y, dReal z);
void dJointSetUniversalAxis1 (dJointID, dReal x, dReal y, dReal z);
void dJointSetUniversalAxis2 (dJointID, dReal x, dReal y, dReal z);
</pre><div class=func2>
Set universal anchor and axis parameters.
Axis 1 and axis 2 should be perpendicular to each other.
</div><p><a name="func_dJointGetUniversalAnchor">
<pre class=func1>
void dJointGetUniversalAnchor (dJointID, dVector3 result);
</pre><div class=func2>
Get the joint anchor point, in world coordinates.  This returns the point on
body 1.  If the joint is perfectly satisfied, this will be the same as the
point on body 2.
</div><p><a name="func_dJointGetUniversalAnchor2">
<pre class=func1>
void dJointGetUniversalAnchor2 (dJointID, dVector3 result);
</pre><div class=func2>
Get the joint anchor point, in world coordinates.  This returns the point on
body 2.  You can think of the ball and socket part of a universal joint as
trying to keep the result of dJointGetBallAnchor() and dJointGetBallAnchor2()
the same.  If the joint is
perfectly satisfied, this function will return the same value
as <a class=func href="#func_dJointGetUniversalAnchor">dJointGetUniversalAnchor</a> to within roundoff errors.  <a class=func href="#func_dJointGetUniversalAnchor2">dJointGetUniversalAnchor2</a>
can be used, along with <a class=func href="#func_dJointGetUniversalAnchor">dJointGetUniversalAnchor</a>, to see how far the joint has come apart.
</div><p><a name="func_dJointGetUniversalAxis1">
<a name="func_dJointGetUniversalAxis2">
<pre class=func1>
void dJointGetUniversalAxis1 (dJointID, dVector3 result);
void dJointGetUniversalAxis2 (dJointID, dVector3 result);
</pre><div class=func2>
Get univeral axis parameters.
</div><h3 class=section3><a name="sec_7_3_5">7.3.5. Hinge-2</a></h3>A hinge-2 joint is shown in figure 8.<p><center>
	<img border=1 src="pix/hinge2.jpg"><br><br>
	<b>Figure 8</b>: A hinge-2 joint.
	</center><p>The hinge-2 joint is the same as two hinges connected in series, with
different hinge axes.
An example, shown in the above picture is the steering wheel of a car,
where one axis allows the wheel to be steered and the other axis allows
the wheel to rotate.<p>The hinge-2 joint has an anchor point and two hinge axes.
Axis 1 is specified relative to body 1 (this would be the steering axis if
body 1 is the chassis).
Axis 2 is specified relative to body 2 (this would be the wheel axis if
body 2 is the wheel).<p>Axis 1 can have joint limits and a motor, axis 2 can only have a motor.<p>Axis 1 can function as a suspension axis, i.e. the constraint can be
compressible along that axis.<p>The hinge-2 joint where axis1 is perpendicular to axis 2 is equivalent to
a universal joint with added suspension.<p><a name="func_dJointSetHinge2Anchor">
<a name="func_dJointSetHinge2Axis1">
<a name="func_dJointSetHinge2Axis2">
<pre class=func1>
void dJointSetHinge2Anchor (dJointID, dReal x, dReal y, dReal z);
void dJointSetHinge2Axis1 (dJointID, dReal x, dReal y, dReal z);
void dJointSetHinge2Axis2 (dJointID, dReal x, dReal y, dReal z);
</pre><div class=func2>
Set hinge-2 anchor and axis parameters.
Axis 1 and axis 2 must not lie along the same line.
</div><p><a name="func_dJointGetHinge2Anchor">
<pre class=func1>
void dJointGetHinge2Anchor (dJointID, dVector3 result);
</pre><div class=func2>
Get the joint anchor point, in world coordinates.  This returns the point on
body 1.  If the joint is perfectly satisfied, this will be the same as the
point on body 2.
</div><p><a name="func_dJointGetHinge2Anchor2">
<pre class=func1>
void dJointGetHinge2Anchor2 (dJointID, dVector3 result);
</pre><div class=func2>
Get the joint anchor point, in world coordinates.  This returns the point on
body 2.  If the joint is perfectly satisfied, this will return the same value
as <a class=func href="#func_dJointGetHinge2Anchor">dJointGetHinge2Anchor</a>.  If not, this value will be slightly different.
This can be used, for example, to see how far the joint has come apart.
</div><p><a name="func_dJointGetHinge2Axis1">
<a name="func_dJointGetHinge2Axis2">
<pre class=func1>
void dJointGetHinge2Axis1 (dJointID, dVector3 result);
void dJointGetHinge2Axis2 (dJointID, dVector3 result);
</pre><div class=func2>
Get hinge-2 axis parameters.
</div><p><a name="func_dJointGetHinge2Angle1">
<a name="func_dJointGetHinge2Angle1Rate">
<a name="func_dJointGetHinge2Angle2Rate">
<pre class=func1>
dReal dJointGetHinge2Angle1 (dJointID);
dReal dJointGetHinge2Angle1Rate (dJointID);
dReal dJointGetHinge2Angle2Rate (dJointID);
</pre><div class=func2>
Get the hinge-2 angles (around axis 1 and axis 2) and the time derivatives
of these values.<p>When the anchor or axis is set, the current position of the attached
bodies is examined and that position will be the zero angle.
</div><h3 class=section3><a name="sec_7_3_6">7.3.6. Fixed</a></h3>The fixed joint maintains a fixed relative position and orientation between
two bodies, or between a body and the static environment.
Using this joint is almost never a good idea in practice, except when
debugging.
If you need two bodies to be glued together it is better to represent that as
a single body.<p><a name="func_dJointSetFixed">
<pre class=func1>
void dJointSetFixed (dJointID);
</pre><div class=func2>
Call this on the fixed joint after it has been attached to remember the
current desired relative offset and desired relative rotation between the bodies.
</div><h3 class=section3><a name="sec_7_3_7">7.3.7. Contact</a></h3>A contact joint is shown in figure 9.<p><center>
	<img border=1 src="pix/contact.jpg"><br><br>
	<b>Figure 9</b>: A contact joint.
	</center><p>The contact joint prevents body 1 and body 2 from inter-penetrating at the
contact point.
It does this by only allowing the bodies to have an ``outgoing'' velocity
in the direction of the contact normal.
Contact joints typically have a lifetime of one time step.
They are created and deleted in response to collision detection.<p>Contact joints can simulate friction at the contact by applying special
forces in the two friction directions that are perpendicular to the
normal.<p>When a contact joint is created, a <span class=c>dContact</span> structure must be supplied.
This has the following definition:
<pre class=code>
struct dContact {
  dSurfaceParameters surface;
  dContactGeom geom;
  dVector3 fdir1;
};</pre>
<span class=c>geom</span> is a substructure that is set by the collision functions.
It is described in the collision section.<p><span class=c>fdir1</span> is a "first friction direction" vector that defines a direction
along which frictional force is applied.
It must be of unit length and perpendicular to the contact normal
(so it is typically tangential to the contact surface).
It should only be defined if the <a class=constref href="#const_dContactFDir1">dContactFDir1</a> flag is set in
<span class=c>surface.mode</span>.
The "second friction direction" is a vector computed to be perpendicular to
both the contact normal and <span class=c>fdir1</span>.<p><span class=c>surface</span> is a substructure that is set by the user.
Its members define the properties of the colliding surfaces.
It has the following members:
<ul>
<li>	<span class=c>int mode</span> - Contact flags. This must always be set.
	This is a combination of one or more of the following flags:<p><center><table border=1 cellspacing=0 cellpadding=6 bgcolor=#ffffc0><tr valign="top"><td><a name="const_dContactMu2"><span class=const>dContactMu2</span></td><td>If not set, use <span class=c>mu</span> for both friction
		directions. If set, use <span class=c>mu</span> for friction direction 1,
		use <span class=c>mu2</span> for friction direction 2.</td></tr><tr valign="top"><td><a name="const_dContactFDir1"><span class=const>dContactFDir1</span></td><td>If set, take <span class=c>fdir1</span> as friction direction
		1, otherwise automatically compute friction direction 1 to be
		perpendicular to the contact normal (in which case its
		resulting orientation is unpredictable).</td></tr><tr valign="top"><td><a name="const_dContactBounce"><span class=const>dContactBounce</span></td><td>If set, the contact surface is bouncy,
		in other words the bodies will bounce off each other.
		The exact amount of bouncyness is controlled by the
		<span class=c>bounce</span> parameter.</td></tr><tr valign="top"><td><a name="const_dContactSoftERP"><span class=const>dContactSoftERP</span></td><td>If set, the error reduction parameter of
		the contact normal can be set with the <span class=c>soft_erp</span> parameter.
		This is useful to make surfaces soft.</td></tr><tr valign="top"><td><a name="const_dContactSoftCFM"><span class=const>dContactSoftCFM</span></td><td>If set, the constraint force mixing
		parameter of the contact normal can be set with the
		<span class=c>soft_cfm</span> parameter. This is useful to make surfaces soft.</td></tr><tr valign="top"><td><a name="const_dContactMotion1"><span class=const>dContactMotion1</span></td><td>If set, the contact surface is assumed to
		be moving independently of the motion of the bodies.
		This is kind of like a conveyor belt running over the surface.
		When this flag is set, <span class=c>motion1</span> defines the surface
		velocity in friction direction 1.</td></tr><tr valign="top"><td><a name="const_dContactMotion2"><span class=const>dContactMotion2</span></td><td>The same thing as above, but for
		friction direction 2.</td></tr><tr valign="top"><td><a name="const_dContactSlip1"><span class=const>dContactSlip1</span></td><td>Force-dependent-slip (FDS) in friction
		direction 1.</td></tr><tr valign="top"><td><a name="const_dContactSlip2"><span class=const>dContactSlip2</span></td><td>Force-dependent-slip (FDS) in friction
		direction 2.</td></tr><tr valign="top"><td><a name="const_dContactApprox1_1"><span class=const>dContactApprox1_1</span></td><td>Use the friction pyramid approximation
		for friction direction 1. If this is not specified then the
		constant-force-limit approximation is used (and <span class=c>mu</span> is a
		force limit).</td></tr><tr valign="top"><td><a name="const_dContactApprox1_2"><span class=const>dContactApprox1_2</span></td><td>Use the friction pyramid approximation
		for friction direction 2. If this is not specified then the
		constant-force-limit approximation is used (and <span class=c>mu</span> is a
		force limit).</td></tr><tr valign="top"><td><a name="const_dContactApprox1"><span class=const>dContactApprox1</span></td><td>Equivalent to both <span class=c>dContactApprox1_1</span>
		and <span class=c>dContactApprox1_2</span>.</td></tr></table></center><p><li>	<span class=c>dReal mu</span> : Coulomb friction coefficient.
	This must be in the range 0 to <span class=c>dInfinity</span>. 0 results in a
	frictionless contact, and <span class=c>dInfinity</span> results in a contact that
	never slips.
	Note that frictionless contacts are less time consuming to compute
	than ones with friction, and infinite friction contacts can be cheaper
	than contacts with finite friction.
	This must always be set.<p><li>	<span class=c>dReal mu2</span> : Optional Coulomb friction coefficient for friction
		direction 2 (0..<span class=c>dInfinity</span>). This is only set if the
		corresponding flag is set in <span class=c>mode</span>.<p><li>	<span class=c>dReal bounce</span> : Restitution parameter (0..1).
	0 means the surfaces are not bouncy at all, 1 is maximum bouncyness.
	This is only set if the corresponding flag is set in <span class=c>mode</span>.<p><li>	<span class=c>dReal bounce_vel</span> : The minimum incoming velocity necessary for
	bounce (in m/s). Incoming velocities below this will effectively have
	a bounce parameter of 0.
	This is only set if the corresponding flag is set in <span class=c>mode</span>.<p><li>	<span class=c>dReal soft_erp</span> : Contact normal ``softness'' parameter.
	This is only set if the corresponding flag is set in <span class=c>mode</span>.<p><li>	<span class=c>dReal soft_cfm</span> : Contact normal ``softness'' parameter.
	This is only set if the corresponding flag is set in <span class=c>mode</span>.<p><li>	<span class=c>dReal motion1,motion2</span> : Surface velocity in friction directions
	1 and 2 (in m/s).
	These are only set if the corresponding flags are set in <span class=c>mode</span>.<p><li>	<span class=c>dReal slip1,slip2</span> : The coefficients of force-dependent-slip (FDS)
	for friction directions 1 and 2.
	These are only set if the corresponding flags are set in <span class=c>mode</span>.<p>FDS is an effect that causes the contacting surfaces to side past each
	other with a velocity that is proportional to the force that is
	being applied tangentially to that surface.<p>Consider a contact point where the coefficient of friction  <i>mu</i>  is
	infinite. Normally, if a force <i>f</i> is applied to the two contacting
	surfaces, to try and get them to slide past each other, they will not
	move.
	However, if the FDS coefficient is set to a positive value <i>k</i>
	then the surfaces will slide past each other, building up to a
	steady velocity of <i>k</i>*<i>f</i> relative to each other.<p>Note that this is quite different from normal frictional effects:
	the force does not cause a constant <i>acceleration</i> of the surfaces
	relative to each other - it causes a brief acceleration to achieve the
	steady velocity.<p>This is useful for modeling some situations, in particular tires.
	For example consider a car at rest on a road.
	Pushing the car in its direction of travel will cause it to start
	moving (i.e. the tires will start rolling).
	Pushing the car in the perpendicular direction will have no effect, as
	the tires do not roll in that direction.
	However - if the car is moving at a velocity <i>v</i>, applying a force
	<i>f</i> in the perpendicular direction will cause the tires to slip on
	the road with a velocity proportional to <i>f</i>*<i>v</i> (Yes, this really
	happens).<p>To model this in ODE set the tire-road contact parameters as follows:
	set friction direction 1 in the direction that the tire is rolling in,
	and set the FDS slip coefficient in friction direction 2 to <i>k</i>*<i>v</i>,
	where <i>v</i> is the tire rolling velocity and <i>k</i> is a tire parameter
	that you can chose based on experimentation.<p>Note that FDS is quite separate from the sticking/slipping effects of
	Coulomb friction - both modes can be used together at a single contact
	point.
</ul><h3 class=section3><a name="sec_7_3_8">7.3.8. Angular Motor</a></h3>An angular motor (AMotor) allows the relative angular velocities of two
bodies to be controlled.
The angular velocity can be controlled on up to three axes, allowing
torque motors and stops to be set for rotation about those axes
(see the ``Stops and motor parameters'' section below).
This is mainly useful in conjunction will ball joints (which do not
constrain the angular degrees of freedom at all), but it can be used in
any situation where angular control is needed.
To use an AMotor with a ball joint, simply attach it to the same two bodies
that the ball joint is attached to.<p>The AMotor can be used in different modes.
In <span class=c>dAMotorUser</span> mode, the user directly sets the axes that the AMotor
controls.
In <span class=c>dAMotorEuler</span> mode, AMotor computes the <i>euler angles</i>
corresponding to the relative rotation, allowing euler angle torque motors
and stops to be set.
An AMotor joint with euler angles is shown in figure 10.<p><center>
	<img border=1 src="pix/amotor.jpg"><br><br>
	<b>Figure 10</b>: An AMotor joint with euler angles.
	</center><p>In this diagram, <i>a</i><sub>0</sub>, <i>a</i><sub>1</sub> and <i>a</i><sub>2</sub> are the three axes along
which angular motion is controlled.
The green axes (including <i>a</i><sub>0</sub>) are anchored to body 1.
The blue axes (including <i>a</i><sub>2</sub>) are anchored to body 2.
To get the body 2 axes from the body 1 axes the following sequence of
rotations is performed:
<ul>
<li>	Rotate by  <i>theta</i> <sub>0</sub> about <i>a</i><sub>0</sub>.
<li>	Rotate by  <i>theta</i> <sub>1</sub> about <i>a</i><sub>1</sub> (<i>a</i><sub>1</sub> has been rotated from its
	original position).
<li>	Rotate by  <i>theta</i> <sub>2</sub> about <i>a</i><sub>2</sub> (<i>a</i><sub>2</sub> has been rotated twice
	from its original position).
</ul><p>There is an important restriction when using euler angles: the  <i>theta</i> <sub>1</sub>
angle must not be allowed to get outside the range - <i>pi</i> /2 ...  <i>pi</i> /2.
If this happens then the AMotor joint will become unstable (there is a
singularity at +/-  <i>pi</i> /2).
Thus you must set the appropriate stops on axis number 1.<p><a name="func_dJointSetAMotorMode">
<a name="func_dJointGetAMotorMode">
<pre class=func1>
void dJointSetAMotorMode (dJointID, int mode);
int dJointGetAMotorMode (dJointID);
</pre><div class=func2>
Set (and get) the angular motor mode. The <span class=arg>mode</span> parameter must be one
of the following constants:<p><center><table border=1 cellspacing=0 cellpadding=6 bgcolor=#ffffc0><tr valign="top"><td><a name="const_dAMotorUser"><span class=const>dAMotorUser</span></td><td>The AMotor axes and joint angle settings are entirely
	controlled by the user.
	This is the default mode.</td></tr><tr valign="top"><td><a name="const_dAMotorEuler"><span class=const>dAMotorEuler</span></td><td>Euler angles are automatically computed.
	The axis <i>a</i><sub>1</sub> is also automatically computed.
	The AMotor axes must be set correctly when in this mode,
	as described below.
	When this mode is initially set the current relative orientations
	of the bodies will correspond to all euler angles at zero.
	</td></tr></table></center>
</div><p><a name="func_dJointSetAMotorNumAxes">
<a name="func_dJointGetAMotorNumAxes">
<pre class=func1>
void dJointSetAMotorNumAxes (dJointID, int num);
int dJointGetAMotorNumAxes (dJointID);
</pre><div class=func2>
Set (and get) the number of angular axes that will be controlled by the
AMotor.
The argument <span class=arg>num</span> can range from 0 (which effectively deactivates the
joint) to 3.
This is automatically set to 3 in <span class=c>dAMotorEuler</span> mode.
</div><p><a name="func_dJointSetAMotorAxis">
<a name="func_dJointGetAMotorAxis">
<a name="func_dJointGetAMotorAxisRel">
<pre class=func1>
void dJointSetAMotorAxis (dJointID, int anum, int rel,
			  dReal x, dReal y, dReal z);
void dJointGetAMotorAxis (dJointID, int anum, dVector3 result);
int dJointGetAMotorAxisRel (dJointID, int anum);
</pre><div class=func2>
Set (and get) the AMotor axes.
The <span class=arg>anum</span> argument selects the axis to change (0,1 or 2).
Each axis can have one of three ``relative orientation'' modes, selected by
<span class=arg>rel</span>:
<ul>
<li> 0: The axis is anchored to the global frame.
<li> 1: The axis is anchored to the first body.
<li> 2: The axis is anchored to the second body.
</ul>
The axis vector (<span class=arg>x</span>,<span class=arg>y</span>,<span class=arg>z</span>) is always specified in global
coordinates regardless of the setting of <span class=arg>rel</span>.
There are two <span class=c>GetAMotorAxis</span> functions, one to return the axis and one to
return the relative mode.<p>For <span class=c>dAMotorEuler</span> mode:
<ul>
<li>	Only axes 0 and 2 need to be set. Axis 1 will be determined
	automatically at each time step.
<li>	Axes 0 and 2 must be perpendicular to each other.
<li>	Axis 0 must be anchored to the first body, axis 2 must be anchored
	to the second body.
</ul>
</div><p><a name="func_dJointSetAMotorAngle">
<pre class=func1>
void dJointSetAMotorAngle (dJointID, int anum, dReal angle);
</pre><div class=func2>
Tell the AMotor what the current angle is along axis <span class=arg>anum</span>.
This function should only be called in <span class=c>dAMotorUser</span> mode, because in this
mode the AMotor has no other way of knowing the joint angles.
The angle information is needed if stops have been set along the axis,
but it is not needed for axis motors.
</div><p><a name="func_dJointGetAMotorAngle">
<pre class=func1>
dReal dJointGetAMotorAngle (dJointID, int anum);
</pre><div class=func2>
Return the current angle for axis <span class=arg>anum</span>.
In <span class=c>dAMotorUser</span> mode this is simply the value that was set with
<a class=func href="#func_dJointSetAMotorAngle">dJointSetAMotorAngle</a>.
In <span class=c>dAMotorEuler</span> mode this is the corresponding euler angle.
</div><p><a name="func_dJointGetAMotorAngleRate">
<pre class=func1>
dReal dJointGetAMotorAngleRate (dJointID, int anum);
</pre><div class=func2>
Return the current angle rate for axis <span class=arg>anum</span>.
In <span class=c>dAMotorUser</span> mode this is always zero, as not enough information is
available.
In <span class=c>dAMotorEuler</span> mode this is the corresponding euler angle rate.
</div><h2 class=section2><a name="sec_7_4_0">7.4. General</a></h2>The joint geometry parameter setting functions should only be called after
the joint has been attached to bodies, and those bodies have been correctly
positioned, otherwise the joint may not be initialized correctly.
If the joint is not already attached, these functions will do nothing.<p>For the parameter getting functions, if the system is out of alignment
(i.e. there is some joint error) then the anchor/axis values will be correct
with respect to body 1 only (or body 2 if you specified body 1 as zero in the
<a class=func href="#func_dJointAttach">dJointAttach</a> function).<p>The default anchor for all joints is (0,0,0).
The default axis for all joints is (1,0,0).<p>When an axis is set it will be normalized to unit length.
The adjusted axis is what the axis getting functions will return.<p>When measuring a joint angle or position, a value of zero corresponds to the
initial position of the bodies relative to each other.<p>Note that there are no functions to set joint angles or positions (or their
rates) directly, instead you must set the corresponding body positions and
velocities.<h2 class=section2><a name="sec_7_5_0">7.5. Stop and motor parameters</a></h2>When a joint is first created there is nothing to prevent it from
moving through its entire range of motion.
For example a hinge will be able to move through its entire angle,
and a slider will slide to any length.<p>This range of motion can be limited by setting stops on the joint.
The joint angle (or position) will be prevented from going below the
low stop value, or from going above the high stop value.
Note that a joint angle (or position) of zero corresponds to the
initial body positions.<p>As well as stops, many joint types can have motors.
A motor applies a torque (or force) to a joint's degree(s) of freedom to
get it to pivot (or slide) at a desired speed.
Motors have force limits, which means they can apply no more than a
given maximum force/torque to the joint.<p>Motors have two parameters: a desired speed, and the maximum force that is
available to reach that speed.
This is a very simple model of real life motors, engines or servos.
However, is it quite useful when modeling a motor (or engine or servo) that
is geared down with a gearbox before being connected to the joint.
Such devices are often controlled by setting a desired speed, and can only
generate a maximum amount of power to achieve that speed (which corresponds
to a certain amount of force available at the joint).<p>Motors can also be used to accurately model dry (or Coulomb) friction in
joints.
Simply set the desired velocity to zero and set the maximum force to some
constant value - then all joint motion will be impeded by that force.<p>The alternative to using joint stops and motors is to simply apply forces
to the affected bodies yourself.
Applying motor forces is easy, and joint stops can be emulated with
restraining spring forces.
However applying forces directly is often not a good approach and can lead
to severe stability problems if it is not done carefully.<p>Consider the case of applying a force to a body to achieve a desired
velocity.
To calculate this force you use information about the current velocity,
something like this:<p><div class=math><i>force</i> = <i>k</i> * (<i>desired</i> <i>speed</i> - <i>current</i> <i>speed</i>)</div><p>This has several problems.
First, the parameter <i>k</i> must be tuned by hand.
If it is too low the body will take a long time to come up to speed.
If it is too high the simulation will become unstable.
Second, even if <i>k</i> is chosen well the body will still take a few time steps
to come up to speed.
Third, if any other ``external'' forces are being applied to the body, the
desired velocity may never even be reached (a more complicated force equation
would be needed, which would have extra parameters and its own problems).<p>Joint motors solve all these problems: they bring the body up to speed
in one time step, provided that does not take more force than is allowed.
Joint motors need no extra parameters because they are actually implemented as
constraints.
They can effectively see one time step into the future to work out the correct
force.
This makes joint motors more computationally expensive than computing the
forces yourself, but they are much more robust and stable, and far less time
consuming to design with.
This is especially true with larger rigid body systems.<p>Similar arguments apply to joint stops.<h3 class=section3><a name="sec_7_5_1">7.5.1. Parameter Functions</a></h3>Here are the functions that set stop and motor parameters (as well as other
kinds of parameters) on a joint:<p><a name="func_dJointSetHingeParam">
<a name="func_dJointSetSliderParam">
<a name="func_dJointSetHinge2Param">
<a name="func_dJointSetUniversalParam">
<a name="func_dJointSetAMotorParam">
<a name="func_dJointGetHingeParam">
<a name="func_dJointGetSliderParam">
<a name="func_dJointGetHinge2Param">
<a name="func_dJointGetUniversalParam">
<a name="func_dJointGetAMotorParam">
<pre class=func1>
void dJointSetHingeParam (dJointID, int parameter, dReal value);
void dJointSetSliderParam (dJointID, int parameter, dReal value);
void dJointSetHinge2Param (dJointID, int parameter, dReal value);
void dJointSetUniversalParam (dJointID, int parameter, dReal value);
void dJointSetAMotorParam (dJointID, int parameter, dReal value);
dReal dJointGetHingeParam (dJointID, int parameter);
dReal dJointGetSliderParam (dJointID, int parameter);
dReal dJointGetHinge2Param (dJointID, int parameter);
dReal dJointGetUniversalParam (dJointID, int parameter);
dReal dJointGetAMotorParam (dJointID, int parameter);
</pre><div class=func2>
Set/get limit/motor parameters for each joint type.
The parameter numbers are:<p><center><table border=1 cellspacing=0 cellpadding=6 bgcolor=#ffffc0><tr valign="top"><td><a name="const_dParamLoStop"><span class=const>dParamLoStop</span></td><td>Low stop angle or position. Setting this to
	<span class=c>-dInfinity</span> (the default value) turns off the low stop.
	For rotational joints, this stop must be greater than - <i>pi</i>  to be
	effective.</td></tr><tr valign="top"><td><a name="const_dParamHiStop"><span class=const>dParamHiStop</span></td><td>High stop angle or position. Setting this to
	<span class=c>dInfinity</span> (the default value) turns off the high stop.
	For rotational joints, this stop must be less than  <i>pi</i>  to be
	effective.
	If the high stop is less than the low stop then both stops will
	be ineffective.</td></tr><tr valign="top"><td><a name="const_dParamVel"><span class=const>dParamVel</span></td><td>Desired motor velocity (this will be an angular or
	linear velocity).</td></tr><tr valign="top"><td><a name="const_dParamFMax"><span class=const>dParamFMax</span></td><td>The maximum force or torque that the motor will use to
	achieve the desired velocity.
	This must always be greater than or equal to zero.
	Setting this to zero (the default value) turns off the motor.</td></tr><tr valign="top"><td><a name="const_dParamFudgeFactor"><span class=const>dParamFudgeFactor</span></td><td>The current joint stop/motor implementation has
	a small problem:
	when the joint is at one stop and the motor is set to move it away
	from the stop, too much force may be applied for one time step,
	causing a ``jumping'' motion.
	This fudge factor is used to scale this excess force.
	It should have a value between zero and one (the default value).
	If the jumping motion is too visible in a joint, the value can be
	reduced.
	Making this value too small can prevent the motor from being able to
	move the joint away from a stop.</td></tr><tr valign="top"><td><a name="const_dParamBounce"><span class=const>dParamBounce</span></td><td>The bouncyness of the stops.
	This is a restitution parameter in the range 0..1.
	0 means the stops are not bouncy at all, 1 means maximum bouncyness.</td></tr><tr valign="top"><td><a name="const_dParamCFM"><span class=const>dParamCFM</span></td><td>The constraint force mixing (CFM) value used when not
	at a stop.</td></tr><tr valign="top"><td><a name="const_dParamStopERP"><span class=const>dParamStopERP</span></td><td>The error reduction parameter (ERP) used by the
	stops.</td></tr><tr valign="top"><td><a name="const_dParamStopCFM"><span class=const>dParamStopCFM</span></td><td>The constraint force mixing (CFM) value used by the
	stops. Together with the ERP value this can be used to get spongy or
	soft stops.
	Note that this is intended for unpowered joints, it does not really
	work as expected when a powered joint reaches its limit.</td></tr><tr valign="top"><td><a name="const_dParamSuspensionERP"><span class=const>dParamSuspensionERP</span></td><td>Suspension error reduction parameter (ERP).
	Currently this is only implemented on the hinge-2 joint.</td></tr><tr valign="top"><td><a name="const_dParamSuspensionCFM"><span class=const>dParamSuspensionCFM</span></td><td>Suspension constraint force mixing (CFM) value.
	Currently this is only implemented on the hinge-2 joint.</td></tr></table></center><p>If a particular parameter is not implemented by a given joint, setting it
will have no effect.<p>These parameter names can be optionally followed by a digit (2 or 3)
to indicate the second or third set of parameters, e.g. for the second axis
in a hinge-2 joint, or the third axis in an AMotor joint.
A constant <span class=c>dParamGroup</span> is also defined such that:
<span class=c>dParamX</span><i>i</i> = <span class=c>dParamX</span> + <span class=c>dParamGroup</span> * (<i>i</i>-1)
</div><h2 class=section2><a name="sec_7_6_0">7.6. Setting Joint Torques/Forces Directly</a></h2>Motors (see above) allow you to set joint velocities directly.  However, you
may instead wish to set the torque or force at a joint instead.  These
functions do just that.  Note that they don't affect the motor, but simply
call <a class=func href="#func_dBodyAddForce">dBodyAddForce</a>/<a class=func href="#func_dBodyAddTorque">dBodyAddTorque</a> on the bodies attached to
it.<p><a name="func_dJointAddHingeTorque">
<pre class=func1>
dJointAddHingeTorque(dJointID joint, dReal torque)
</pre><div class=func2>
Applies the torque about the hinge axis.  That is, it applies a torque with
magnitude <span class=arg>torque</span>, in the direction of the hinge axis, to body 1, and
with the same magnitude but in opposite direction to body 2.  This function
is just a wrapper for <a class=func href="#func_dBodyAddTorque">dBodyAddTorque</a>
</div><p><a name="func_dJointAddUniversalTorques">
<pre class=func1>
dJointAddUniversalTorques(dJointID joint, dReal torque1, dReal torque2)
</pre><div class=func2>
Applies <span class=arg>torque1</span> about the universal's axis 1, and <span class=arg>torque2</span> about the
universal's axis 2.  This function is just a wrapper for <a class=func href="#func_dBodyAddTorque">dBodyAddTorque</a>.
</div><p><a name="func_dJointAddSliderForce">
<pre class=func1>
dJointAddSliderForce(dJointID joint, dReal force)
</pre><div class=func2>
Applies the given force in the slider's direction.  That is, it applies a force
with magnitude <span class=arg>force</span>, in the direction slider's axis, to body1, and with
the same magnitude but opposite direction to body2.  This function is just a
wrapper for <a class=func href="#func_dBodyAddForce">dBodyAddForce</a>.
</div><p><a name="func_dJointAddHinge2Torques">
<pre class=func1>
dJointAddHinge2Torques(dJointID joint, dReal torque1, dReal torque2)
</pre><div class=func2>
Applies <span class=arg>torque1</span> about the hinge2's axis 1, and <span class=arg>torque2</span> about the
hinge2's axis 2.  This function is just a wrapper for <a class=func href="#func_dBodyAddTorque">dBodyAddTorque</a>.
</div><p><a name="func_dJointAddAMotorTorques">
<pre class=func1>
dJointAddAMotorTorques(dJointID joint, dReal torque0, dReal torque1,
                       dReal torque2)
</pre><div class=func2>
Applies <span class=arg>torque0</span> about the AMotor's axis 0, <span class=arg>torque1</span> about the
AMotor's axis 1, and <span class=arg>torque2</span> about the AMotor's axis 2.  If the motor has
fewer than three axes, the higher torques are ignored.  This function is just a
wrapper for <a class=func href="#func_dBodyAddTorque">dBodyAddTorque</a>.
</div><h1 class=section1><a name="sec_8_0_0">8. StepFast</a></h1><b>NOTE: The StepFast algorithm has been superseded by the QuickStep algorithm:
see the <a class=func href="#func_dWorldQuickStep">dWorldQuickStep</a> function.
However, much of the following discussion also applies to QuickStep, except for
the details of the method used.</b><p>ODE's <a class=func href="#func_dWorldStep">dWorldStep</a> function currently uses a "big matrix" method to
step the system. For some large systems this can be slow and can require
a lot of memory.
The StepFast1 algorithm provides an alternative way to step the system,
that sacrifices some accuracy for a big gain in speed and memory.
To use it, you simply call <a class=func href="#func_dWorldStepFast1">dWorldStepFast1</a> instead of
<a class=func href="#func_dWorldStep">dWorldStep</a>.<p>The chart in figure 11 illustrates this speed advantage over the standard
<a class=func href="#func_dWorldStep">dWorldStep</a> algorithm.<p><center>
	<img border=1 src="pix/sf-graph1.jpg"><br><br>
	<b>Figure 11</b>: Speed advantage of StepFast.
	</center><p>The graph relates the number of Degrees Of Freedom (DOFs) removed from a
system to the running time of the step. You may be able to tell that the
<a class=func href="#func_dWorldStep">dWorldStep</a> algorithm's running time is proportional to the cube of the
number of DOF's removed. The StepFast1 algorithm, however, is roughly
linear. So as islands increase in size (for example, when there is a large
pile-up of cars, a pile of "ragdoll corpses", or a wall of bricks) the
StepFast1 algorithm scales better than <a class=func href="#func_dWorldStep">dWorldStep</a>. All this means that
your application is more likely to keep a steady framerate, even in the
worst case scenario.<p>The graph of DOFs removed to memory looks quite similar (see figure 12).<p><center>
	<img border=1 src="pix/sf-graph2.jpg"><br><br>
	<b>Figure 12</b>: Memory advantage of StepFast.
	</center><p><a class=func href="#func_dWorldStep">dWorldStep</a> requires memory proportional only to the square of the
number of DOF's removed. StepFast1, though, is still linear, but it has
nothing to do with the number of iterations per step. So this means the
dreaded "There was a big pile-up and ODE crashed without an error message"
problems (usually stack overflows) won't happen with StepFast1. Or at
least that you'll be rendering at a minute per frame or slower before
they do.<h2 class=section2><a name="sec_8_1_0">8.1. When to use StepFast1</a></h2>As shown above, StepFast1 is quite good when it comes to speed and memory
usage. All this power doesn't come for free, though; all optimizations are
a trade-off of one kind or another. I've already mentioned that StepFast1
trades off accuracy for it's speed and memory advantages. You actually get
to choose just how much accuracy you give away though, at the cost of speed,
by adjusting the number of iterations per step. Though you may never reach
the accuracy of <a class=func href="#func_dWorldStep">dWorldStep</a> (or you may surpass it, depending on the
type of inaccuracy), you can be almost certain that a larger number of
iterations will give you more accurate results (more slowly). So StepFast1
can be used in a good variety of situations.<p>The general answer to this question then, is: use StepFast1 when you don't
mind having a few more parameters to play with to get the system stable,
and you want to take advantage of it's speed or memory advantages. If you
find yourself running into situations in your simulation where large numbers
of bodies come in contact, and <a class=func href="#func_dWorldStep">dWorldStep</a> becomes too slow, try
switching to StepFast1. Many systems will work just fine with nothing more
than changing the <a class=func href="#func_dWorldStep">dWorldStep</a> function call to <a class=func href="#func_dWorldStepFast1">dWorldStepFast1</a>.
Others will require a little tweaking to get them to work well with
StepFast1, usually in the masses of the bodies. When a joint connects two
bodies with a large mass ratio (i.e. one body has several times the mass
of the other body) StepFast1 may have trouble solving it.<p>Another prospect for StepFast1 is designing for it from the ground up.
If you know you are going to build large worlds with many physically based
objects in them, then go ahead and plan to use StepFast1. Noting the mass
ratio problem above, you might want to consider making the mass of every
body in your system equal to 1.0. Or in a very small range, for example
between 0.5 and 1.5. Most of the other suggestions for speed and stability
apply to StepFast1, except that the object is no longer to remove as many
joints as possible from the equation. It can likely be shown that you will
get a better performance to stability ratio by spreading out mass among
several bodies connected by fixed joints rather than trying to implement
it as one massive body, especially if that one massive body means you have
to switch back to <a class=func href="#func_dWorldStep">dWorldStep</a> to keep things stable.<p>A final prospect for StepFast1 is to use it only when you need to.
Since StepFast1 uses the body and world structures in exactly the same
way as <a class=func href="#func_dWorldStep">dWorldStep</a>, you can actually switch back and forth between the two
solvers at will. A good heuristic for when to make this switch is to
simply count contact joints while you are running the collision detection.
Since collision detection is normally called before the step, using this
method will ensure that the large island that would slow you down is never
sent to the <a class=func href="#func_dWorldStep">dWorldStep</a> solver (as opposed to waiting until after you've
already taken a step at 1 fps...). The only better solution would be a
hybrid island creation function, that sends small islands to <a class=func href="#func_dWorldStep">dWorldStep</a>,
and large islands to <a class=func href="#func_dWorldStepFast1">dWorldStepFast1</a>. This may make it in the source at
some point in the future.<h2 class=section2><a name="sec_8_2_0">8.2. When NOT to use StepFast1</a></h2>Though there are several specific situations when it as advisable not to
use StepFast1, I believe they can all be summed up in a single statement:
Don't use StepFast1 when accuracy is more important than speed or memory
to you. You may still want to evaluate it in this case and see if the
inaccuracies are even noticeable, perhaps with a relatively large number
of iterations (20+).<h2 class=section2><a name="sec_8_3_0">8.3. How it works</a></h2>For any interested parties out there, here's a quick rundown of how the
StepFast1 algorithm works. The general problem that ODE tries to solve
is a system of linear (in)equalities in (<i>m</i> = constraints) unknowns,
where one constraint constrains 1 Degree of Freedom in one joint.
For large islands of bodies with many joints between them, this can
take a rather large <i>O</i>(<i>m</i><sup>2</sup>) array, which takes <i>O</i>(<i>m</i><sup>3</sup>) time to solve.
StepFast1 completely avoids creating the large matrix by making an
assumption: at relatively small timesteps, the effect of any given joint
is so localized that it can be calculated without respect to any other
joint in the system, and any conflicting joints will cancel each other
out before the body actually moves. So StepFast1 uses the same solution
method (LCP) to solve the same problem, only localized to a single joint
(where m &lt;= 6). It gets away with this by sub-dividing the timestep and
repeating the process over really small timesteps (i = maxiterations) times.
So the running time of StepFast1 is "roughly" <i>O</i>(<i>m</i> <i>i</i>). It's really closer
to <i>O</i>(<i>j</i> <i>i</i> (<i>m</i>/<i>j</i>)<sup>3</sup>) = <i>O</i>(<i>m</i> <i>i</i> (<i>m</i>/<i>j</i>)<sup>2</sup>), where <i>j</i> = joints, but (<i>m</i>/<i>j</i>)
is never &gt; 6, so (<i>m</i>/<i>j</i>)<sup>2</sup> is factored out as a constant.<h2 class=section2><a name="sec_8_4_0">8.4. Experimental Utilities included with StepFast1</a></h2>Several experimental functions have been added to ODE as part of the
StepFast1 flow of code, at least until they are validated. Most have to do
with the automatic disabling and enabling of bodies as yet another bit of
optimization.  Here's the general idea:<p><ul>
<li>	The body is considered a candidate for disabling when it falls
	below a certain speed (linear and angular), called the
	AutoDisableThreshold. In the interest of speedy execution, the actual
	speed measured is the square of the speed of the body. So you may
	need to set a lower value than you expected. 0.003 works well in
	test_crash, and is the default.
<li>	When the body has remained a disable candidate for a certain number
	of steps (AutoDisableSteps), it is disabled. This is almost completely
	for boxes, which like to land and bounce up on two points, and teeter
	motionless for a few steps before falling back down. Round items
	generally need a much lower (like 1) AutoDisableSteps than boxes do
	(10+), 10 is the default.
<li>	AutoDisabling is disabled by default, use
	dBodySetAutoDisableSF1(body, true) to enable it.
<li>	A body is automatically re-enabled when it comes in contact with
	another enabled body.
<li>	Enabled bodies only enable bodies within (AutoEnableDepth) bodies
	of them each step. This, in conjunction with AutoDisabling, causes a
	rim of bodies that are enabled and disabled each step to form,
	containing the enabled bodies to the smallest area allowed by the
	AutoDisable parameters. Setting AutoEnableDepth to a really large
	number will retain the current functionality. Setting it to 0 will
	give you a new functionality: disabled bodies will never be
	automatically re-enabled, acting like geoms only. 3 seems to be a
	good value for the wall in test_crash, but 1000 is the default to
	retain standard functionality.
</ul><p>Note that the functions pertaining to auto-disabling are not yet implemented!<h2 class=section2><a name="sec_8_5_0">8.5. API</a></h2><a name="func_dWorldStepFast1">
<pre class=func1>
void dWorldStepFast1(dWorldID, dReal stepsize, int maxiterations);
</pre><div class=func2>
Step the world by <span class=arg>stepsize</span> seconds using the StepFast1 algorithm.
The number of iterations to perform is given by <span class=arg>maxiterations</span>.
</div><p><a name="func_dWorldSetAutoEnableDepthSF1">
<a name="func_dWorldGetAutoEnableDepthSF1">
<pre class=func1>
void dWorldSetAutoEnableDepthSF1(dWorldID, int autoEnableDepth);
int dWorldGetAutoEnableDepthSF1(dWorldID);
</pre><div class=func2>
Set and get the AutoEnableDepth parameter used by the StepFast1 algorithm.
</div><p><a name="func_dBodySetAutoDisableThresholdSF1">
<a name="func_dBodyGetAutoDisableThresholdSF1">
<pre class=func1>
void dBodySetAutoDisableThresholdSF1(dBodyID, dReal autoDisableThreshold);
dReal dBodyGetAutoDisableThresholdSF1(dBodyID);
</pre><div class=func2>
Set and get the per-body AutoDisableThreshold parameter used by the
StepFast1 algorithm.
</div><p><a name="func_dBodySetAutoDisableStepsSF1">
<a name="func_dBodyGetAutoDisableStepsSF1">
<pre class=func1>
void dBodySetAutoDisableStepsSF1(dBodyID, int AutoDisableSteps);
int dBodyGetAutoDisableStepsSF1(dBodyID);
</pre><div class=func2>
Set and get the per-body AutoDisableSteps parameter used by the StepFast1
algorithm.
</div><p><a name="func_dBodySetAutoDisableSF1">
<a name="func_dBodyGetAutoDisableSF1">
<pre class=func1>
void dBodySetAutoDisableSF1(dBodyID, int doAutoDisable);
int dBodyGetAutoDisableSF1(dBodyID);
</pre><div class=func2>
Set and get the per-body AutoDisable flag used by the StepFast1 algorithm.
If <span class=arg>doAutoDisable</span> is nonzero, auto-disabling is enabled.
If <span class=arg>doAutoDisable</span> is zero, auto-disabling is disabled.
</div><h1 class=section1><a name="sec_9_0_0">9. Support Functions</a></h1><h2 class=section2><a name="sec_9_1_0">9.1. Rotation functions</a></h2>Rigid body orientations are represented with quaternions.
A quaternion is four numbers [<i>cos</i>( <i>theta</i> /2),<i>sin</i>( <i>theta</i> /2)*<i>u</i>]
where  <i>theta</i>  is a rotation angle and <i>u</i> is a unit length rotation
axis.<p>Every rigid body also has a 3x3 rotation matrix that is derived from
the quaternion.
The rotation matrix and the quaternion always match.<p>Some information about quaternions:
<ul>
<li>	q and -q represent the same rotation.
<li>	The inverse of a quaternion is [ <i>q</i>[0] -<i>q</i>[1] -<i>q</i>[2] -<i>q</i>[3] ].
</ul><p>The following are utility functions for dealing with rotation matrices and
quaternions.<p><a name="func_dRSetIdentity">
<pre class=func1>
void dRSetIdentity (dMatrix3 R);
</pre><div class=func2>
Set <span class=arg>R</span> to the identity matrix (i.e. no rotation).
</div><p><a name="func_dRFromAxisAndAngle">
<pre class=func1>
void dRFromAxisAndAngle (dMatrix3 R,
                         dReal ax, dReal ay, dReal az, dReal angle);
</pre><div class=func2>
Compute the rotation matrix <span class=arg>R</span> as a rotation of <span class=arg>angle</span> radians
along the axis (<span class=arg>ax</span>,<span class=arg>ay</span>,<span class=arg>az</span>).
</div><p><a name="func_dRFromEulerAngles">
<pre class=func1>
void dRFromEulerAngles (dMatrix3 R,
                        dReal phi, dReal theta, dReal psi);
</pre><div class=func2>
Compute the rotation matrix <span class=arg>R</span> from the three Euler rotation angles.
</div><p><a name="func_dRFrom2Axes">
<pre class=func1>
void dRFrom2Axes (dMatrix3 R, dReal ax, dReal ay, dReal az,
                  dReal bx, dReal by, dReal bz);
</pre><div class=func2>
Compute the rotation matrix <span class=arg>R</span> from the two vectors `a'
(<span class=arg>ax</span>,<span class=arg>ay</span>,<span class=arg>az</span>) and `b' (<span class=arg>bx</span>,<span class=arg>by</span>,<span class=arg>bz</span>).
`a' and `b' are the desired x and y axes of the rotated coordinate system.
If necessary, `a' and `b' will be made unit length, and `b' will be
projected so that it is perpendicular to `a'.
The desired z axis is the cross product of `a' and `b'.
</div><p><a name="func_dQSetIdentity">
<pre class=func1>
void dQSetIdentity (dQuaternion q);
</pre><div class=func2>
Set <span class=arg>q</span> to the identity rotation (i.e. no rotation).
</div><p><a name="func_dQFromAxisAndAngle">
<pre class=func1>
void dQFromAxisAndAngle (dQuaternion q, dReal ax, dReal ay, dReal az,
                         dReal angle);
</pre><div class=func2>
Compute <span class=arg>q</span> as a rotation of <span class=arg>angle</span> radians along the axis
(<span class=arg>ax</span>,<span class=arg>ay</span>,<span class=arg>az</span>).
</div><p><a name="func_dQMultiply0">
<a name="func_dQMultiply1">
<a name="func_dQMultiply2">
<a name="func_dQMultiply3">
<pre class=func1>
void dQMultiply0 (dQuaternion qa,
                  const dQuaternion qb, const dQuaternion qc);
void dQMultiply1 (dQuaternion qa,
                  const dQuaternion qb, const dQuaternion qc);
void dQMultiply2 (dQuaternion qa,
                  const dQuaternion qb, const dQuaternion qc);
void dQMultiply3 (dQuaternion qa,
                  const dQuaternion qb, const dQuaternion qc);
</pre><div class=func2>
Set <span class=arg>qa</span> = <span class=arg>qb</span>*<span class=arg>qc</span>.
This is that same as <span class=arg>qa</span> = rotation <span class=arg>qc</span> followed by rotation
<span class=arg>qb</span>.
The 0/1/2 versions are analogous to the multiply functions, i.e. 1 uses the
inverse of <span class=arg>qb</span>, and 2 uses the inverse of <span class=arg>qc</span>.
Option 3 uses the inverse of both.
</div><p><a name="func_dQtoR">
<pre class=func1>
void dQtoR (const dQuaternion q, dMatrix3 R);
</pre><div class=func2>
Convert quaternion <span class=arg>q</span> to rotation matrix <span class=arg>R</span>.
</div><p><a name="func_dRtoQ">
<pre class=func1>
void dRtoQ (const dMatrix3 R, dQuaternion q);
</pre><div class=func2>
Convert rotation matrix <span class=arg>R</span> to quaternion <span class=arg>q</span>.
</div><p><a name="func_dWtoDQ">
<pre class=func1>
void dWtoDQ (const dVector3 w, const dQuaternion q, dVector4 dq);
</pre><div class=func2>
Given an existing orientation <span class=arg>q</span> and an angular velocity vector <span class=arg>w</span>,
return in <span class=arg>dq</span> the resulting dq/dt.
</div><h2 class=section2><a name="sec_9_2_0">9.2. Mass functions</a></h2>The mass parameters of a rigid body are described by a <span class=c>dMass</span> structure:
<pre class=code>
typedef struct dMass {
  dReal mass;   // total mass of the rigid body
  dVector4 c;   // center of gravity position in body frame (x,y,z)
  dMatrix3 I;   // 3x3 inertia tensor in body frame, about POR
} dMass;</pre><p>The following functions operate on this structure:<p><a name="func_dMassSetZero">
<pre class=func1>
void dMassSetZero (dMass *);
</pre><div class=func2>
Set all the mass parameters to zero.
</div><p><a name="func_dMassSetParameters">
<pre class=func1>
void dMassSetParameters (dMass *, dReal themass,
                         dReal cgx, dReal cgy, dReal cgz,
                         dReal I11, dReal I22, dReal I33,
                         dReal I12, dReal I13, dReal I23);
</pre><div class=func2>
Set the mass parameters to the given values.
<span class=arg>themass</span> is the mass of the body.
(<span class=arg>cx</span>,<span class=arg>cy</span>,<span class=arg>cz</span>) is the center of gravity position in the body
frame.
The <span class=c>Ixx</span> values are the elements of the inertia matrix:
<pre class=code>
    [ I11 I12 I13 ]
    [ I12 I22 I23 ]
    [ I13 I23 I33 ]</pre>
</div><p><a name="func_dMassSetSphere">
<a name="func_dMassSetSphereTotal">
<pre class=func1>
void dMassSetSphere (dMass *, dReal density, dReal radius);
void dMassSetSphereTotal (dMass *, dReal total_mass, dReal radius);
</pre><div class=func2>
Set the mass parameters to represent a sphere of the given radius and
density, with the center of mass at (0,0,0) relative to the body.  The
first function accepts the density of the sphere, the second accepts
the total mass of the sphere.
</div><p><a name="func_dMassSetCappedCylinder">
<a name="func_dMassSetCappedCylinderTotal">
<pre class=func1>
void dMassSetCappedCylinder (dMass *, dReal density, int direction,
                             dReal radius, dReal length);
void dMassSetCappedCylinderTotal (dMass *, dReal total_mass,
                             int direction, dReal radius, dReal length);
</pre><div class=func2>
Set the mass parameters to represent a capped cylinder of the given parameters
and density, with the center of mass at (0,0,0) relative to the body.
The radius of the cylinder (and the spherical cap) is <span class=arg>radius</span>.
The length of the cylinder (not counting the spherical cap) is <span class=arg>length</span>.
The cylinder's long axis is oriented along the body's x, y or z axis according
to the value of <span class=arg>direction</span> (1=x, 2=y, 3=z).  The
first function accepts the density of the object, the second accepts
its total mass.
</div><p><a name="func_dMassSetCylinder">
<a name="func_dMassSetCylinderTotal">
<pre class=func1>
void dMassSetCylinder (dMass *, dReal density, int direction,
		       dReal radius, dReal length);
void dMassSetCylinderTotal (dMass *, dReal total_mass, int direction,
		       dReal radius, dReal length);
</pre><div class=func2>
Set the mass parameters to represent a flat-ended cylinder of the given
parameters and density, with the center of mass at (0,0,0) relative to the
body.
The radius of the cylinder is <span class=arg>radius</span>.
The length of the cylinder is <span class=arg>length</span>.
The cylinder's long axis is oriented along the body's x, y or z axis according
to the value of <span class=arg>direction</span> (1=x, 2=y, 3=z).  The
first function accepts the density of the object, the second accepts
its total mass.
</div><p><a name="func_dMassSetBox">
<a name="func_dMassSetBoxTotal">
<pre class=func1>
void dMassSetBox (dMass *, dReal density,
                  dReal lx, dReal ly, dReal lz);
void dMassSetBoxTotal (dMass *, dReal total_mass,
                  dReal lx, dReal ly, dReal lz);
</pre><div class=func2>
Set the mass parameters to represent a box of the given dimensions
and density, with the center of mass at (0,0,0) relative to the body.
The side lengths of the box along the x, y and z axes are <span class=arg>lx</span>, <span class=arg>ly</span>
and <span class=arg>lz</span>.  The
first function accepts the density of the object, the second accepts
its total mass.
</div><p><a name="func_dMassAdjust">
<pre class=func1>
void dMassAdjust (dMass *, dReal newmass);
</pre><div class=func2>
Given mass parameters for some object, adjust them so the total mass is
now <span class=arg>newmass</span>.
This is useful when using the above functions to set the mass parameters for
certain objects - they take the object density, not the total mass.
</div><p><a name="func_dMassTranslate">
<pre class=func1>
void dMassTranslate (dMass *, dReal x, dReal y, dReal z);
</pre><div class=func2>
Given mass parameters for some object, adjust them to represent the object
displaced by (<span class=arg>x</span>,<span class=arg>y</span>,<span class=arg>z</span>) relative to the body frame.
</div><p><a name="func_dMassRotate">
<pre class=func1>
void dMassRotate (dMass *, const dMatrix3 R);
</pre><div class=func2>
Given mass parameters for some object, adjust them to represent the object
rotated by <span class=arg>R</span> relative to the body frame.
</div><p><a name="func_dMassAdd">
<pre class=func1>
void dMassAdd (dMass *a, const dMass *b);
</pre><div class=func2>
Add the mass <span class=arg>b</span> to the mass <span class=arg>a</span>.
</div><h2 class=section2><a name="sec_9_3_0">9.3. Math functions</a></h2>[There are quite a lot of these, but they're not standardized enough to
document yet].<h2 class=section2><a name="sec_9_4_0">9.4. Error and memory functions</a></h2>[Document these later].<h1 class=section1><a name="sec_10_0_0">10. Collision Detection</a></h1>ODE has two main components: a dynamics simulation engine and a collision
detection engine.
The collision engine is given information about the <i>shape</i> of each
body. At each time step it figures out which bodies touch each other and
passes the resulting contact point information to the user.
The user in turn creates contact joints between bodies.<p>Using ODE's collision detection is optional - an alternative collision
detection system can be used as long as it can supply the right kinds
of contact information.<h2 class=section2><a name="sec_10_1_0">10.1. Contact points</a></h2>If two bodies touch, or if a body touches a static feature in its environment,
the contact is represented by one or more "contact points".
Each contact point has a corresponding <span class=c>dContactGeom</span> structure:
<pre class=code>
struct dContactGeom {
  dVector3 pos;       // contact position
  dVector3 normal;    // normal vector
  dReal depth;        // penetration depth
  dGeomID g1,g2;      // the colliding geoms
};</pre>
<span class=arg>pos</span> records the contact position, in global coordinates.<p><span class=arg>depth</span> is the depth to which the two bodies inter-penetrate each other.
If the depth is zero then the two bodies have a grazing contact, i.e. they
"only just" touch.
However, this is rare - the simulation is not perfectly accurate and will
often step the bodies too far so that the depth is nonzero.<p><span class=arg>normal</span> is a unit length vector that is, generally speaking,
perpendicular to the contact surface.<p><span class=arg>g1</span> and <span class=arg>g2</span> are the geometry objects that collided.<p>The convention is that if body 1 is moved along the <span class=arg>normal</span> vector by a
distance <span class=arg>depth</span> (or equivalently if body 2 is moved the same distance in
the opposite direction) then the contact depth will be reduced to zero.
This means that the normal vector points "in" to body 1.<p>In real life, contact between two bodies is a complex thing.
Representing contacts by contact points is only an approximation.
Contact "patches" or "surfaces" might be more physically accurate, but
representing these things in high speed simulation software is a challenge.<p>Each extra contact point added to the simulation will slow it down some more,
so sometimes we are forced to ignore contact points in the interests of speed.
For example, when two boxes collide many contact points may be needed to
properly represent the geometry of the situation, but we may choose to
keep only the best three. Thus we are piling approximation on top of
approximation.<h2 class=section2><a name="sec_10_2_0">10.2. Geoms</a></h2>Geometry objects (or ``geoms'' for short) are the fundamental objects
in the collision system. A geom can represents a single rigid shape
(such as a sphere or box), or it can represents a group of
other geoms - this is a special kind of geom called a ``space''.<p>Any geom can be collided against any other geom to yield zero or more
contact points. Spaces have the extra capability of being able to
collide their contained geoms together to yield internal contact
points.<p>Geoms can be placeable or non-placeable. A placeable geom has a
position vector and a 3*3 rotation matrix, just like a rigid body,
that can be changed during the simulation.
A non-placeable geom does not have this capability - for example, it
may represent some static feature of the environment that can not be
moved. Spaces are non-placeable geoms, because each contained geom may
have its own position and orientation but it does not make sense for
the space itself to have a position and orientation.<p>To use the collision engine in a rigid body simulation, placeable
geoms are associated with rigid body objects. This allows the
collision engine to get the position and orientation of the geoms from
the bodies. Note that geoms are distinct from rigid bodies in that a
geom has geometrical properties (size, shape, position and
orientation) but no dynamical properties (such as velocity or mass).
A body and a geom together represent all the properties of the
simulated object.<p>Every geom is an instance of a <i>class</i>, such as sphere, plane, or
box. There are a number of built-in classes, described below, and you
can define your own classes as well.<p>The point of reference of a placeable geoms is the point that is
controlled by its position vector. The point of reference for the
standard classes usually corresponds to the geom's center of
mass. This feature allows the standard classes to be easily connected
to dynamics bodies. If other points of reference are required, a
transformation object can be used to encapsulate a geom.<p>The concepts and functions that apply to all geoms will be described
below, followed by the various geometry classes and the functions that
manipulate them.<h2 class=section2><a name="sec_10_3_0">10.3. Spaces</a></h2>A space is a non-placeable geom that can contain other geoms.
It is similar to the rigid body concept of the ``world'', except that
it applies to collision instead of dynamics.<p>Space objects exist to make collision detection go faster.
Without spaces, you might generate contacts in your simulation by
calling <a class=func href="#func_dCollide">dCollide</a> to get contact points for every single
pair of geoms.
For N geoms this is <i>O</i>(<i>N</i><sup>2</sup>) tests, which is too computationally
expensive if your environment has many objects.<p>A better approach is to insert the geoms into a space and call
<a class=func href="#func_dSpaceCollide">dSpaceCollide</a>.
The space will then perform collision culling, which means
that it will quickly identify which pairs of geoms are <i>potentially</i>
intersecting.
Those pairs will be passed to a callback function, which can in turn
call <a class=func href="#func_dCollide">dCollide</a> on them.
This saves a lot of time that would have been spent in useless
<a class=func href="#func_dCollide">dCollide</a> tests, because the number of pairs passed to the
callback function will be a small fraction of every possible
object-object pair.<p>Spaces can contain other spaces. This is useful for dividing a
collision environment into several hierarchies to further optimize
collision detection speed. This will be described in more detail
below.<h2 class=section2><a name="sec_10_4_0">10.4. General geom functions</a></h2>The following functions can be applied to any geom.<p><a name="func_dGeomDestroy">
<pre class=func1>
void dGeomDestroy (dGeomID);
</pre><div class=func2>
Destroy a geom, removing it from any space it is in first.  This one
function destroys a geom of any type, but to create a geom you must
call a creation function for that type.<p>When a space is destroyed, if its cleanup mode is 1 (the default) then
all the geoms in that space are automatically destroyed as well.
</div><p><a name="func_dGeomSetData">
<a name="func_dGeomGetData">
<pre class=func1>
void dGeomSetData (dGeomID, void *);
void *dGeomGetData (dGeomID);
</pre><div class=func2>
These functions set and get the user-defined data pointer stored in the
geom.
</div><p><a name="func_dGeomSetBody">
<a name="func_dGeomGetBody">
<pre class=func1>
void dGeomSetBody (dGeomID, dBodyID);
dBodyID dGeomGetBody (dGeomID);
</pre><div class=func2>
These functions set and get the body associated with a placeable geom.
Setting a body on a geom automatically combines the position vector
and rotation matrix of the body and geom, so that setting the position
or orientation of one will set the value for both objects.<p>Setting a body ID of zero gives the geom its own position and
rotation, independent from any body. If the geom was previously connected
to a body then its new independent position/rotation is set to the current
position/rotation of the body.<p>Calling these functions on a non-placeable geom results in a runtime
error in the debug build of ODE.
</div><p><a name="func_dGeomSetPosition">
<a name="func_dGeomSetRotation">
<a name="func_dGeomSetQuaternion">
<pre class=func1>
void dGeomSetPosition (dGeomID, dReal x, dReal y, dReal z);
void dGeomSetRotation (dGeomID, const dMatrix3 R);
void dGeomSetQuaternion (dGeomID, const dQuaternion);
</pre><div class=func2>
Set the position vector, rotation matrix or quaternion of a placeable geom.
These functions are analogous to <a class=func href="#func_dBodySetPosition">dBodySetPosition</a>,
<a class=func href="#func_dBodySetRotation">dBodySetRotation</a> and <a class=func href="#func_dBodySetQuaternion">dBodySetQuaternion</a>.
If the geom is attached to a body, the body's position / rotation / quaternion
will also be changed.<p>Calling these functions on a non-placeable geom results in a runtime
error in the debug build of ODE.
</div><p><a name="func_dGeomGetPosition">
<a name="func_dGeomGetRotation">
<a name="func_dGeomGetQuaternion">
<pre class=func1>
const dReal * dGeomGetPosition (dGeomID);
const dReal * dGeomGetRotation (dGeomID);
void dGeomGetQuaternion (dGeomID, dQuaternion result);
</pre><div class=func2>
The first two return pointers to the geom's position vector and rotation matrix.
The returned values are pointers to internal data structures, so the vectors
are valid until any changes are made to the geom.
If the geom is attached to a body, the body's position / rotation
pointers will be returned, i.e. the result will be identical to calling
<a class=func href="#func_dBodyGetPosition">dBodyGetPosition</a> or <a class=func href="#func_dBodyGetRotation">dBodyGetRotation</a>.<p><a class=func href="#func_dGeomGetQuaternion">dGeomGetQuaternion</a> copies the geom's quaternion into the space provided.
If the geom is attached to a body, the body's quaternion will be returned, i.e.
the resulting quaternion will be the same as the result of calling
<a class=func href="#func_dBodyGetQuaternion">dBodyGetQuaternion</a>.<p>Calling these functions on a non-placeable geom results in a runtime
error in the debug build of ODE.
</div><p><a name="func_dGeomGetAABB">
<pre class=func1>
void dGeomGetAABB (dGeomID, dReal aabb[6]);
</pre><div class=func2>
Return in <span class=arg>aabb</span> an axis aligned bounding box that surrounds the
given geom.
The <span class=arg>aabb</span> array has elements (<i>minx</i>, <i>maxx</i>, <i>miny</i>, <i>maxy</i>, <i>minz</i>, <i>maxz</i>).
If the geom is a space, a bounding box that surrounds all contained
geoms is returned.<p>This function may return a pre-computed cached bounding box, if it can
determine that the geom has not moved since the last time the bounding
box was computed.
</div><p><a name="func_dGeomIsSpace">
<pre class=func1>
int dGeomIsSpace (dGeomID);
</pre><div class=func2>
Return 1 if the given geom is a space, or 0 if not.
</div><p><a name="func_dGeomGetSpace">
<pre class=func1>
dSpaceID dGeomGetSpace (dGeomID);
</pre><div class=func2>
Return the space that the given geometry is contained in, or return 0 if it is
not contained in any space.
</div><p><a name="func_dGeomGetClass">
<pre class=func1>
int dGeomGetClass (dGeomID);
</pre><div class=func2>
Given a geom, this returns its class number.
The standard class numbers are:<p><center><table border=1 cellspacing=0 cellpadding=6 bgcolor=#ffffc0><tr valign="top"><td><a name="const_dSphereClass"><span class=const>dSphereClass</span></td><td>Sphere</td></tr><tr valign="top"><td><a name="const_dBoxClass"><span class=const>dBoxClass</span></td><td>Box</td></tr><tr valign="top"><td><a name="const_dCCylinderClass"><span class=const>dCCylinderClass</span></td><td>Capped cylinder</td></tr><tr valign="top"><td><a name="const_dCylinderClass"><span class=const>dCylinderClass</span></td><td>Regular flat-ended cylinder</td></tr><tr valign="top"><td><a name="const_dPlaneClass"><span class=const>dPlaneClass</span></td><td>Infinite plane (non-placeable)</td></tr><tr valign="top"><td><a name="const_dGeomTransformClass"><span class=const>dGeomTransformClass</span></td><td>Geometry transform</td></tr><tr valign="top"><td><a name="const_dRayClass"><span class=const>dRayClass</span></td><td>Ray</td></tr><tr valign="top"><td><a name="const_dTriMeshClass"><span class=const>dTriMeshClass</span></td><td>Triangle mesh</td></tr><tr valign="top"><td><a name="const_dSimpleSpaceClass"><span class=const>dSimpleSpaceClass</span></td><td>Simple space</td></tr><tr valign="top"><td><a name="const_dHashSpaceClass"><span class=const>dHashSpaceClass</span></td><td>Hash table based space</td></tr></table></center><p>User defined classes will return their own numbers.
</div><p><a name="func_dGeomSetCategoryBits">
<a name="func_dGeomSetCollideBits">
<a name="func_dGeomGetCategoryBits">
<a name="func_dGeomGetCollideBits">
<pre class=func1>
void dGeomSetCategoryBits (dGeomID, unsigned long bits);
void dGeomSetCollideBits (dGeomID, unsigned long bits);
unsigned long dGeomGetCategoryBits (dGeomID);
unsigned long dGeomGetCollideBits (dGeomID);
</pre><div class=func2>
Set and get the ``category'' and ``collide'' bitfields for the given geom.
These bitfields are use by spaces to govern which geoms will interact
with each other.
The bit fields are guaranteed to be at least 32 bits wide.
The default category and collide values for newly created geoms have
all bits set.
</div><p><a name="func_dGeomEnable">
<a name="func_dGeomDisable">
<a name="func_dGeomIsEnabled">
<pre class=func1>
void dGeomEnable (dGeomID);
void dGeomDisable (dGeomID);
int dGeomIsEnabled (dGeomID);
</pre><div class=func2>
Enable and disable a geom.
Disabled geoms are completely ignored by <a class=func href="#func_dSpaceCollide">dSpaceCollide</a> and
<a class=func href="#func_dSpaceCollide2">dSpaceCollide2</a>, although they can still be members of a space.<p><span class=c>dGeomIsEnabled()</span> returns 1 if a geom is enabled or 0 if it is disabled.
New geoms are created in the enabled state.
</div><h2 class=section2><a name="sec_10_5_0">10.5. Collision detection</a></h2>A collision detection ``world'' is created by making a space and then adding
geoms to that space.
At every time step we want to generate a list of contacts for all the geoms
that intersect each other.
Three functions are used to do this:
<ul>
<li>	<a class=func href="#func_dCollide">dCollide</a> intersects two geoms and generates contact points.<p><li>	<a class=func href="#func_dSpaceCollide">dSpaceCollide</a> determines which pairs of geoms in a space
	may potentially intersect, and calls a callback function with each
	candidate pair.
	This does not generate contact points directly, because the user may
	want to handle some pairs specially - for example by ignoring
	them or using different contact generating strategies.
	Such decisions are made in the callback function, which can choose
	whether or not to call <a class=func href="#func_dCollide">dCollide</a> for each pair.<p><li>	<a class=func href="#func_dSpaceCollide2">dSpaceCollide2</a> determines which geoms from one space
	may potentially intersect with geoms from another space,
	and calls a callback function with each candidate pair.
	It can also test a single non-space geom against a space.
	This function is useful when there is a collision hierarchy, i.e.
	when there are spaces that contain other spaces.
</ul><p>The collision system has been designed to give the user maximum
flexibility to decide which objects will be tested against each other.
This is why are there are three collision functions instead of, for example,
one function that just generates all the contact points.<p>Spaces may contain other spaces. These sub-spaces will typically
represent a collection of geoms (or other spaces) that are located
near each other.
This is useful for gaining extra collision performance by dividing the
collision world into hierarchies. Here is an example of where this is
useful:<p>Suppose you have two cars driving over some terrain. Each car is made
up of many geoms. If all these geoms were inserted into the same
space, the collision computation time between the two cars would
always be proportional to the total number of geoms (or even to the
square of this number, depending on which space type is used).<p>To speed up collision a separate space is created to represent each
car. The car geoms are inserted into the car-spaces, and the
car-spaces are inserted into the top level space.  At each time step
<a class=func href="#func_dSpaceCollide">dSpaceCollide</a> is called for the top level space. This will do
a single intersection test between the car-spaces (actually between
their bounding boxes) and call the callback if they touch.
The callback can then test the geoms in the car-spaces against each
other using <a class=func href="#func_dSpaceCollide2">dSpaceCollide2</a>. If the cars are not near each
other then the callback is not called and no time is wasted performing
unnecessary tests.<p>If space hierarchies are being used then the callback function may be
called recursively, e.g. if <a class=func href="#func_dSpaceCollide">dSpaceCollide</a> calls the callback
which in turn calls <a class=func href="#func_dSpaceCollide">dSpaceCollide</a> with the same callback function.
In this case the user must make sure that the callback function is
properly reentrant.<p>Here is a sample callback function that traverses through all spaces
and sub-spaces, generating all possible contact points for all
intersecting geoms:<p><pre class=code>
  void nearCallback (void *data, dGeomID o1, dGeomID o2)
  {
    if (dGeomIsSpace (o1) || dGeomIsSpace (o2)) {
      // colliding a space with something
      dSpaceCollide2 (o1,o2,data,&amp;nearCallback);
      // collide all geoms internal to the space(s)
      if (dGeomIsSpace (o1)) dSpaceCollide (o1,data,&amp;nearCallback);
      if (dGeomIsSpace (o2)) dSpaceCollide (o2,data,&amp;nearCallback);
    }
    else {
      // colliding two non-space geoms, so generate contact
      // points between o1 and o2
      int num_contact = dCollide (o1,o2,max_contacts,contact_array,skip);
      // add these contact points to the simulation
      ...
    }
  }

  ...

  // collide all objects together
  dSpaceCollide (top_level_space,0,&amp;nearCallback);</pre><p>A space callback function is not allowed to modify a space while that
space is being processed with <a class=func href="#func_dSpaceCollide">dSpaceCollide</a> or
<a class=func href="#func_dSpaceCollide2">dSpaceCollide2</a>. For example, you can not add or remove geoms
from a space, and you can not reposition the geoms within a space.
Doing so will trigger a runtime error in the debug build of ODE.<h3 class=section3><a name="sec_10_5_1">10.5.1. Category and Collide Bitfields</a></h3>Each geom has a ``category'' and ``collide'' bitfield that can be used
to assist the space algorithms in determining which geoms should
interact and which should not. Use of this feature is optional - by
default geoms are considered to be capable of colliding with any
other geom.<p>Each bit position in the bitfield represents a different category of
object. The actual meaning of these categories (if any) is user defined.
The category bitfield indicates which categories a geom is a member of.
The collide bitfield indicates which categories the geom will collide with
during collision detection.<p>A pair of geoms will be considered by <a class=func href="#func_dSpaceCollide">dSpaceCollide</a> and
<a class=func href="#func_dSpaceCollide2">dSpaceCollide2</a> for passing to the callback only if one of them
has a collide bit set that corresponds to a category bit in the other.
The exact test is as follows:<p><pre class=code>
  // test if geom o1 and geom o2 can collide
  cat1 = dGeomGetCategoryBits (o1);
  cat2 = dGeomGetCategoryBits (o2);
  col1 = dGeomGetCollideBits (o1);
  col2 = dGeomGetCollideBits (o2);
  if ((cat1 &amp; col2) || (cat2 &amp; col1)) {
    // call the callback with o1 and o2
  }
  else {
    // do nothing, o1 and o2 do not collide
  }</pre><p>Note that only <a class=func href="#func_dSpaceCollide">dSpaceCollide</a> and <a class=func href="#func_dSpaceCollide2">dSpaceCollide2</a> use
these bitfields, they are ignored by <a class=func href="#func_dCollide">dCollide</a>.<p>Typically a geom will belong only to a single category, so only one bit will
be set in the category bitfield.
The bitfields are guaranteed to be at least 32 bits wide, so the user is
able to specify an arbitrary pattern of interactions for up to 32 objects.
If there are more than 32 objects then some of them will obviously have
to have the same category.<p>Sometimes the category field will contain multiple bits set, e.g. if
the geom is a space them you may want to set the category to the union of
all the geom categories that are contained.<p><b>Design note:</b> Why don't we just have a single category bitfield and
use the test <span class=c>(cat1 &amp; cat2)</span> ? This is simpler, but a single field
requires more bits to represent some patterns of interaction.
For example, if 32 geoms have an interaction pattern that is a 5
dimensional hypercube, 80 bit are required in the simpler scheme.
The simpler scheme also makes it harder to determine what the
categories should be for some situations.<h3 class=section3><a name="sec_10_5_2">10.5.2. Collision Detection Functions</a></h3><a name="func_dCollide">
<pre class=func1>
int dCollide (dGeomID o1, dGeomID o2, int flags,
              dContactGeom *contact, int skip);
</pre><div class=func2>
Given two geoms <span class=arg>o1</span> and <span class=arg>o2</span> that potentially intersect,
generate contact information for them.
Internally, this just calls the correct class-specific collision functions
for <span class=arg>o1</span> and <span class=arg>o2</span>.<p><span class=arg>flags</span> specifies how contacts should be generated if the geoms touch.
The lower 16 bits of <span class=arg>flags</span> is an integer that specifies the maximum
number of contact points to generate.
Note that if this number is zero, this function just pretends that it
is one - in other words you can not ask for zero contacts.
All other bits in <span class=arg>flags</span> must be zero.
In the future the other bits may be used to select from different contact
generation strategies.<p><span class=arg>contact</span> points to an array of <span class=c>dContactGeom</span> structures.
The array must be able to hold at least the maximum number of contacts.
These <span class=c>dContactGeom</span> structures may be embedded within larger structures
in the array - the <span class=arg>skip</span> parameter is the byte offset from one
<span class=c>dContactGeom</span> to the next in the array.
If <span class=arg>skip</span> is <span class=c>sizeof(dContactGeom)</span> then <span class=arg>contact</span> points to a
normal (C-style) array.
It is an error for <span class=arg>skip</span> to be smaller than <span class=c>sizeof(dContactGeom)</span>.<p>If the geoms intersect, this function returns the number of contact
points generated (and updates the <span class=arg>contact</span> array), otherwise it
returns 0 (and the <span class=arg>contact</span> array is not touched).<p>If a space is passed as <span class=arg>o1</span> or <span class=arg>o2</span> then this function will collide
all objects contained in <span class=arg>o1</span> with all objects contained in <span class=arg>o2</span>,
and return the resulting contact points.
This method for colliding spaces with geoms (or spaces with spaces) provides
no user control over the individual collisions.
To get that control, use <a class=func href="#func_dSpaceCollide">dSpaceCollide</a> or <a class=func href="#func_dSpaceCollide2">dSpaceCollide2</a>
instead.<p>If <span class=arg>o1</span> and <span class=arg>o2</span> are the same geom then this function will do
nothing and return 0. Technically speaking an object intersects with
itself, but it is not useful to find contact points in this case.<p>This function does not care if <span class=arg>o1</span> and <span class=arg>o2</span> are in the same
space or not (or indeed if they are in any space at all).
</div><p><a name="func_dSpaceCollide">
<pre class=func1>
void dSpaceCollide (dSpaceID space,
                    void *data, dNearCallback *callback);
</pre><div class=func2>
This determines which pairs of geoms in a space may potentially intersect,
and calls the callback function with each candidate pair.
The <span class=arg>callback</span> function is of type <span class=c>dNearCallback</span>, which is defined as:
<pre class=code>
typedef void dNearCallback (void *data, dGeomID o1, dGeomID o2);</pre>
The <span class=arg>data</span> argument is passed from <a class=func href="#func_dSpaceCollide">dSpaceCollide</a> directly
to the callback function. Its meaning is user defined.
The <span class=arg>o1</span> and <span class=arg>o2</span> arguments are the geoms that may be near
each other.<p>The callback function can call <a class=func href="#func_dCollide">dCollide</a> on <span class=arg>o1</span> and
<span class=arg>o2</span> to generate contact points between each pair.
Then these contact points may be added to the simulation as contact
joints.
The user's callback function can of course chose not to call
<a class=func href="#func_dCollide">dCollide</a> for any pair, e.g. if the user decides that
those pairs should not interact.<p>Other spaces that are contained within the colliding space are not
treated specially, i.e. they are not recursed into.
The callback function may be passed these contained spaces as one or
both geom arguments.<p><span class=c>dSpaceCollide()</span> is guaranteed to pass all intersecting geom pairs
to the callback function, but it may also make mistakes and pass
non-intersecting pairs. The number of mistaken calls depends on the
internal algorithms used by the space.
Thus you should not expect that <a class=func href="#func_dCollide">dCollide</a> will return
contacts for every pair passed to the callback.
</div><p><a name="func_dSpaceCollide2">
<pre class=func1>
void dSpaceCollide2 (dGeomID o1, dGeomID o2,
                     void *data, dNearCallback *callback);
</pre><div class=func2><p>This function is similar to <a class=func href="#func_dSpaceCollide">dSpaceCollide</a>, except that it is
passed two geoms (or spaces) as arguments.
It calls the callback for all potentially intersecting pairs that contain
one geom from <span class=arg>o1</span> and one geom from <span class=arg>o2</span>.<p>The exact behavior depends on the types of <span class=arg>o1</span> and <span class=arg>o2</span>:
<ul>
<li>	If one argument is a non-space geom and the other is a space,
	the callback is called with all potential intersections between
	the geom and the objects in the space.
<li>	If both <span class=arg>o1</span> and <span class=arg>o2</span> are spaces then this calls the
	callback for all potentially intersecting pairs that contain
	one geom from <span class=arg>o1</span> and one geom from <span class=arg>o2</span>.
	The algorithm that is used depends on what kinds of spaces are
	being collided. If no optimized algorithm can be selected then
	this function will resort to one of the following two strategies:
	<ol>
	<li>	All the geoms in <span class=arg>o1</span> are tested one-by-one against
		<span class=arg>o2</span>.
	<li>	All the geoms in <span class=arg>o2</span> are tested one-by-one against
		<span class=arg>o1</span>.
	</ol>
	The strategy used may depends on a number of rules, but in general
	the space with less objects has its geoms examined one-by-one.
<li>	If both arguments are the same space, this is equivalent to
	calling <a class=func href="#func_dSpaceCollide">dSpaceCollide</a> on that space.
<li>	If both arguments are non-space geoms, this simply calls the
	callback once with these arguments.
</ul>
If this function is given a space and an geom X in that same space,
this case is not treated specially. In this case the callback will
always be called with the pair (X,X), because an objects always
intersects with itself.
The user may either test for this case and ignore it, or just pass the
pair (X,X) to <a class=func href="#func_dCollide">dCollide</a> (which will be guaranteed to return 0).
</div><h2 class=section2><a name="sec_10_6_0">10.6. Space functions</a></h2>There are several kinds of spaces. Each kind uses different internal
data structures to store the geoms, and different algorithms to
perform the collision culling:
<ul>
<li>	Simple space. This does not do any collision culling - it simply
	checks every possible pair of geoms for intersection, and reports
	the pairs whose AABBs overlap.
	The time required to do intersection testing for <i>n</i> objects is
	<i>O</i>(<i>n</i><sup>2</sup>).
	This should not be used for large numbers of objects, but it can be
	the preferred algorithm for a small number of objects.
	This is also useful for debugging potential problems with the
	collision system.<p><li>	Multi-resolution hash table space.
	This uses an internal data structure that records how each geom
	overlaps cells in one of several three dimensional grids.
	Each grid has cubical cells of side lengths 2<sup><i>i</i></sup>, where <i>i</i>
	is an integer that ranges from a minimum to a maximum value.
	The time required to do intersection testing for <i>n</i> objects is
	<i>O</i>(<i>n</i>) (as long as those objects are not clustered together too
	closely), as each object can be quickly paired with the objects
	around it.<p><li>	Quadtree space. This uses a pre-allocated hierarchical grid-based
	AABB tree to quickly cull collision checks. It's exceptionally
	quick for large amounts of objects in landscape-shaped worlds.
	The amount of memory used is 4^depth * 32 bytes.
	Currently <a class=func href="#func_dSpaceGetGeom">dSpaceGetGeom</a> is not implemented for the quadtree
	space.
</ul><p>Here are the functions used for spaces:<p><a name="func_dSimpleSpaceCreate">
<a name="func_dHashSpaceCreate">
<pre class=func1>
dSpaceID dSimpleSpaceCreate (dSpaceID space);
dSpaceID dHashSpaceCreate (dSpaceID space);
</pre><div class=func2>
Create a space, either of the simple or multi-resolution hash table kind.
If <span class=arg>space</span> is nonzero, insert the new space into that space.
</div><p><a name="func_dQuadTreeSpaceCreate">
<pre class=func1>
dSpaceID dQuadTreeSpaceCreate (dSpaceID space, dVector3 Center,
                               dVector3 Extents, int Depth);
</pre><div class=func2>
Creates a quadtree space. <span class=arg>center</span> and <span class=arg>extents</span> define the size
of the root block. <span class=arg>depth</span> sets the depth of the tree - the number
of blocks that are created is 4^depth.
</div><p><a name="func_dSpaceDestroy">
<pre class=func1>
void dSpaceDestroy (dSpaceID);
</pre><div class=func2>
This destroys a space. It functions exactly like <a class=func href="#func_dGeomDestroy">dGeomDestroy</a>
except that it takes a <span class=c>dSpaceID</span> argument.
When a space is destroyed, if its cleanup mode is 1 (the default) then
all the geoms in that space are automatically destroyed as well.
</div><p><a name="func_dHashSpaceSetLevels">
<a name="func_dHashSpaceGetLevels">
<pre class=func1>
void dHashSpaceSetLevels (dSpaceID space, int minlevel, int maxlevel);
void dHashSpaceGetLevels (dSpaceID space, int *minlevel, int *maxlevel);
</pre><div class=func2>
Sets and get some parameters for a multi-resolution hash table space.
The smallest and largest cell sizes used in the hash table will be
2^<span class=arg>minlevel</span> and 2^<span class=arg>maxlevel</span> respectively.
<span class=arg>minlevel</span> must be less than or equal to <span class=arg>maxlevel</span>.<p>In <a class=func href="#func_dHashSpaceGetLevels">dHashSpaceGetLevels</a> the minimum and maximum levels are returned
through pointers. If a pointer is zero then it is ignored and no
argument is returned.
</div><p><a name="func_dSpaceSetCleanup">
<a name="func_dSpaceGetCleanup">
<pre class=func1>
void dSpaceSetCleanup (dSpaceID space, int mode);
int dSpaceGetCleanup (dSpaceID space);
</pre><div class=func2>
Set and get the clean-up mode of the space.
If the clean-up mode is 1, then the contained geoms will be destroyed when
the space is destroyed. If the clean-up mode is 0 this does not happen.
The default clean-up mode for new spaces is 1.
</div><p><a name="func_dSpaceAdd">
<pre class=func1>
void dSpaceAdd (dSpaceID, dGeomID);
</pre><div class=func2>
Add a geom to a space.
This does nothing if the geom is already in the space.
This function can be called automatically if a <span class=arg>space</span> argument is
given to a geom creation function.
</div><p><a name="func_dSpaceRemove">
<pre class=func1>
void dSpaceRemove (dSpaceID, dGeomID);
</pre><div class=func2>
Remove a geom from a space.
This does nothing if the geom is not actually in the space.
This function is called automatically by <a class=func href="#func_dGeomDestroy">dGeomDestroy</a> if the
geom is in a space.
</div><p><a name="func_dSpaceQuery">
<pre class=func1>
int dSpaceQuery (dSpaceID, dGeomID);
</pre><div class=func2>
Return 1 if the given geom is in the given space, or return 0 if it is not.
</div><p><a name="func_dSpaceGetNumGeoms">
<pre class=func1>
int dSpaceGetNumGeoms (dSpaceID);
</pre><div class=func2>
Return the number of geoms contained within a space.
</div><p><a name="func_dSpaceGetGeom">
<pre class=func1>
dGeomID dSpaceGetGeom (dSpaceID, int i);
</pre><div class=func2>
Return the <span class=arg>i</span>'th geom contained within the space.
<span class=arg>i</span> must range from 0 to <span class=arg>dSpaceGetNumGeoms()</span>-1.<p>If any change is made to the space (including adding and deleting geoms)
then no guarantee can be made about how the index number of any particular
geom will change.
Thus no space changes should be made while enumerating the geoms.<p>This function is guaranteed to be fastest when the geoms are accessed in
the order 0,1,2,etc. Other non-sequential orders may result in slower access,
depending on the internal implementation.
</div><h2 class=section2><a name="sec_10_7_0">10.7. Geometry Classes</a></h2><h3 class=section3><a name="sec_10_7_1">10.7.1. Sphere Class</a></h3><a name="func_dCreateSphere">
<pre class=func1>
dGeomID dCreateSphere (dSpaceID space, dReal radius);
</pre><div class=func2>
Create a sphere geom of the given <span class=arg>radius</span>, and return its ID.
If <span class=arg>space</span> is nonzero, insert it into that space.
The point of reference for a sphere is its center.
</div><p><a name="func_dGeomSphereSetRadius">
<pre class=func1>
void dGeomSphereSetRadius (dGeomID sphere, dReal radius);
</pre><div class=func2>
Set the radius of the given sphere.
</div><p><a name="func_dGeomSphereGetRadius">
<pre class=func1>
dReal dGeomSphereGetRadius (dGeomID sphere);
</pre><div class=func2>
Return the radius of the given sphere.
</div><p><a name="func_dGeomSpherePointDepth">
<pre class=func1>
dReal dGeomSpherePointDepth (dGeomID sphere, dReal x, dReal y, dReal z);
</pre><div class=func2>
Return the depth of the point (<span class=arg>x</span>,<span class=arg>y</span>,<span class=arg>z</span>) in the given sphere.
Points inside the geom will have positive depth, points outside it will have
negative depth, and points on the surface will have zero depth.
</div><h3 class=section3><a name="sec_10_7_2">10.7.2. Box Class</a></h3><a name="func_dCreateBox">
<pre class=func1>
dGeomID dCreateBox (dSpaceID space, dReal lx, dReal ly, dReal lz);
</pre><div class=func2>
Create a box geom of the given x/y/z side lengths
(<span class=arg>lx</span>,<span class=arg>ly</span>,<span class=arg>lz</span>), and return its ID.
If <span class=arg>space</span> is nonzero, insert it into that space.
The point of reference for a box is its center.
</div><p><a name="func_dGeomBoxSetLengths">
<pre class=func1>
void dGeomBoxSetLengths (dGeomID box, dReal lx, dReal ly, dReal lz);
</pre><div class=func2>
Set the side lengths of the given <span class=arg>box</span>.
</div><p><a name="func_dGeomBoxGetLengths">
<pre class=func1>
void dGeomBoxGetLengths (dGeomID box, dVector3 result);
</pre><div class=func2>
Return in <span class=arg>result</span> the side lengths of the given <span class=arg>box</span>.
</div><p><a name="func_dGeomBoxPointDepth">
<pre class=func1>
dReal dGeomBoxPointDepth (dGeomID box, dReal x, dReal y, dReal z);
</pre><div class=func2>
Return the depth of the point (<span class=arg>x</span>,<span class=arg>y</span>,<span class=arg>z</span>) in the given box.
Points inside the geom will have positive depth, points outside it will have
negative depth, and points on the surface will have zero depth.
</div><h3 class=section3><a name="sec_10_7_3">10.7.3. Plane Class</a></h3><a name="func_dCreatePlane">
<pre class=func1>
dGeomID dCreatePlane (dSpaceID space,
                      dReal a, dReal b, dReal c, dReal d);
</pre><div class=func2>
Create a plane geom of the given parameters, and return its ID.
If <span class=arg>space</span> is nonzero, insert it into that space.
The plane equation is <div class=math><i>a</i>*<i>x</i>+<i>b</i>*<i>y</i>+<i>c</i>*<i>z</i> = <i>d</i></div>
The plane's normal vector is (<i>a</i>,<i>b</i>,<i>c</i>), and it must have length 1.
Planes are non-placeable geoms. This means that, unlike placeable geoms,
planes do not have an assigned position and rotation.
This means that the parameters (a,b,c,d) are always in global coordinates.
In other words it is assumed that the plane is always part of the static
environment and not tied to any movable object.
</div><p><a name="func_dGeomPlaneSetParams">
<pre class=func1>
void dGeomPlaneSetParams (dGeomID plane, dReal a, dReal b, dReal c, dReal d);
</pre><div class=func2>
Set the parameters of the given <span class=arg>plane</span>.
</div><p><a name="func_dGeomPlaneGetParams">
<pre class=func1>
void dGeomPlaneGetParams (dGeomID plane, dVector4 result);
</pre><div class=func2>
Return in <span class=arg>result</span> the parameters of the given <span class=arg>plane</span>.
</div><p><a name="func_dGeomPlanePointDepth">
<pre class=func1>
dReal dGeomPlanePointDepth (dGeomID plane, dReal x, dReal y, dReal z);
</pre><div class=func2>
Return the depth of the point (<span class=arg>x</span>,<span class=arg>y</span>,<span class=arg>z</span>) in the given plane.
Points inside the geom will have positive depth, points outside it will have
negative depth, and points on the surface will have zero depth.
</div><h3 class=section3><a name="sec_10_7_4">10.7.4. Capped Cylinder Class</a></h3><a name="func_dCreateCCylinder">
<pre class=func1>
dGeomID dCreateCCylinder (dSpaceID space, dReal radius, dReal length);
</pre><div class=func2>
Create a capped cylinder geom of the given parameters, and return
its ID.
If <span class=arg>space</span> is nonzero, insert it into that space.<p>A capped cylinder is like a normal cylinder except it has half-sphere caps
at its ends.
This feature makes the internal collision detection code particularly fast
and accurate.
The cylinder's length, not counting the caps, is given by <span class=arg>length</span>.
The cylinder is aligned along the geom's local Z axis.
The radius of the caps, and of the cylinder itself, is given by <span class=arg>radius</span>.
</div><p><a name="func_dGeomCCylinderSetParams">
<pre class=func1>
void dGeomCCylinderSetParams (dGeomID ccylinder,
                              dReal radius, dReal length);
</pre><div class=func2>
Set the parameters of the given capped cylinder.
</div><p><a name="func_dGeomCCylinderGetParams">
<pre class=func1>
void dGeomCCylinderGetParams (dGeomID ccylinder,
                              dReal *radius, dReal *length);
</pre><div class=func2>
Return in <span class=arg>radius</span> and <span class=arg>length</span> the parameters of the given capped
cylinder.
</div><p><a name="func_dGeomCCylinderPointDepth">
<pre class=func1>
dReal dGeomCCylinderPointDepth (dGeomID ccylinder,
                                dReal x, dReal y, dReal z);
</pre><div class=func2>
Return the depth of the point (<span class=arg>x</span>,<span class=arg>y</span>,<span class=arg>z</span>) in the given capped
cylinder.
Points inside the geom will have positive depth, points outside it will have
negative depth, and points on the surface will have zero depth.
</div><h3 class=section3><a name="sec_10_7_5">10.7.5. Ray Class</a></h3>A ray is different from all the other geom classes in that it does not
represent a solid object. It is an infinitely thin line that starts from
the geom's position and extends in the direction of the geom's local Z-axis.<p>Calling <a class=func href="#func_dCollide">dCollide</a> between a ray and another geom will result in at
most one contact point.
Rays have their own conventions for the contact information in the
<span class=c>dContactGeom</span> structure (thus it is not useful to create contact joints
from this information):<p><ul>
<li>	<span class=c>pos</span> - This is the point at which the ray intersects the surface of
	the other geom, regardless of whether the ray starts from inside or
	outside the geom.<p><li>	<span class=c>normal</span> - This is the surface normal of the other geom at the
	contact point.
	if <a class=func href="#func_dCollide">dCollide</a> is passed the ray as its first geom then the
	normal will be oriented correctly for ray reflection from that surface
	(otherwise it will have the opposite sign).<p><li>	<span class=c>depth</span> - This is the distance from the start of the ray to the
	contact point.
</ul><p>Rays are useful for things like visibility testing, determining the
path of projectiles or light rays, and for object placement.<p><a name="func_dCreateRay">
<pre class=func1>
dGeomID dCreateRay (dSpaceID space, dReal length);
</pre><div class=func2>
Create a ray geom of the given length, and return its ID.
If <span class=arg>space</span> is nonzero, insert it into that space.
</div><p><a name="func_dGeomRaySetLength">
<pre class=func1>
void dGeomRaySetLength (dGeomID ray, dReal length);
</pre><div class=func2>
Set the length of the given <span class=arg>ray</span>.
</div><p><a name="func_dGeomRayGetLength">
<pre class=func1>
dReal dGeomRayGetLength (dGeomID ray);
</pre><div class=func2>
Get the length of the given <span class=arg>ray</span>.
</div><p><a name="func_dGeomRaySet">
<pre class=func1>
void dGeomRaySet (dGeomID ray, dReal px, dReal py, dReal pz,
                  dReal dx, dReal dy, dReal dz);
</pre><div class=func2>
Set the starting position (<span class=arg>px</span>,<span class=arg>py</span>,<span class=arg>pz</span>) and direction
(<span class=arg>dx</span>,<span class=arg>dy</span>,<span class=arg>dz</span>) of the given <span class=arg>ray</span>.
The ray's rotation matrix will be adjusted so that the local Z-axis is
aligned with the direction.
Note that this does not adjust the ray's length.
</div><p><a name="func_dGeomRayGet">
<pre class=func1>
void dGeomRayGet (dGeomID ray, dVector3 start, dVector3 dir);
</pre><div class=func2>
Get the starting position (<span class=arg>start</span>) and direction (<span class=arg>dir</span>) of the
ray. The returned direction will be a unit length vector.
</div><h3 class=section3><a name="sec_10_7_6">10.7.6. Triangle Mesh Class</a></h3>A triangle mesh (TriMesh) represents an arbitrary collection of
triangles.
The triangle mesh collision system has the following features:
<ul>
<li>	Any triangle ``soup'' can be represented --- i.e. the triangles
	are not required to have any particular strip, fan or grid
	structure.
<li>	Triangle meshes can interact with spheres, boxes, rays and other triangle meshes.
<li>	It works well for relatively large triangles.
<li>	It uses temporal coherence to speed up collision tests.
	When a geom has its collision checked with a trimesh once,
	data is stored inside the trimesh.
	This data can be cleared with the <a class=func href="#func_dGeomTriMeshClearTCCache">dGeomTriMeshClearTCCache</a>
	function.
	In the future it will be possible to disable this functionality.
</ul><p>Trimesh/Trimesh collisions, perform quite well, but there are three minor caveats:<p><ul>
<li> The stepsize you use will, in general, have to be reduced for
   accurate collision resolution.  Non-convex shape collision is much
   more dependent on the collision geometry than primitive collisions.
   Further, the local contact geometry will change more rapidly (and
   in a more complex fashion) for non-convex polytopes than it does
   for simple, convex polytopes such as spheres and cubes.<p><li> In order to efficiently resolve collisions, dCollideTTL needs
   the positions of the colliding trimeshes in the previous timestep.
   This is used to calculate an estimated velocity of each colliding
   triangle, which is used to find the direction of impact, contact
   normals, etc.  This requires
   the user to update these variables at every timestep.
   This update is performed outside of ODE, so it is not included
   in ODE itself.  The code to do this looks something like this:
<pre class=code>
  const double *DoubleArrayPtr =
    Bodies[BodyIndex].TransformationMatrix-&gt;GetArray();
  dGeomTriMeshDataSet( TriMeshData,
    TRIMESH_LAST_TRANSFORMATION,
    (void *) DoubleArrayPtr );</pre><p>The transformation matrix is the standard 4x4 homogeneous transform
   matrix, and the "DoubleArray" is the standard flattened array of
   the 16 matrix values.
</ul><p><b>NOTE: The triangle mesh class is not final, so in the future API changes
might be expected.</b><p><a name="func_dGeomTriMeshDataCreate">
<a name="func_dGeomTriMeshDataDestroy">
<pre class=func1>
dTriMeshDataID dGeomTriMeshDataCreate();
void dGeomTriMeshDataDestroy (dTriMeshDataID g);
</pre><div class=func2>
Creates and destroys a dTriMeshData object which is used to store
mesh data.
</div><p><a name="func_dGeomTriMeshDataBuild">
<pre class=func1>
void dGeomTriMeshDataBuild (dTriMeshDataID g, const void* Vertices,
                            int VertexStride, int VertexCount,
			    const void* Indices, int IndexCount,
                            int TriStride, const void* Normals);
</pre><div class=func2>
Used for filling a <span class=c>dTriMeshData</span> object with data. No data is copied
here, so the pointers passed into this function must remain valid.
This is how the strided data works:<p><pre class=code>
struct StridedVertex {
  dVector3 Vertex;  // 4th component can be left out, reducing memory usage
  // Userdata
};
int VertexStride = sizeof (StridedVertex);

struct StridedTri {
  int Indices[3];
  // Userdata
};
int TriStride = sizeof (StridedTri);</pre><p>The <span class=c>Normals</span> argument is optional: the normals of the faces of each trimesh object.  For example,<p><pre class=code>
  dTriMeshDataID TriMeshData;
  TriMeshData = dGeomTriMeshGetTriMeshDataID (
        Bodies[BodyIndex].GeomID);

  // as long as dReal == floats
  dGeomTriMeshDataBuildSingle (TriMeshData,
        // Vertices
        Bodies[BodyIndex].VertexPositions,
        3*sizeof(dReal), (int) numVertices,
        // Faces
        Bodies[BodyIndex].TriangleIndices,
        (int) NumTriangles, 3*sizeof(unsigned int),
        // Normals
        Bodies[BodyIndex].FaceNormals);</pre><p>This pre-calculation saves some time during evaluation of the
contacts, but isn't necessary.  If you don't want to calculate
the face normals before construction (or if you have enormous
trimeshes and know that only very few faces will be touching
and want to save time), just pass a "NULL" for the <span class=c>Normals</span> argument,
and dCollideTTL will take care of the normal calculations itself.
</div><p><a name="func_dGeomTriMeshDataBuildSimple">
<pre class=func1>
void dGeomTriMeshDataBuildSimple (dTriMeshDataID g, const dVector3*Vertices,
                                  int VertexCount, const int* Indices,
                                  int IndexCount);
</pre><div class=func2>
Simple build function provided for convenience.
</div><p><a name="func_dTriCallback">
<a name="func_dGeomTriMeshSetCallback">
<a name="func_dGeomTriMeshGetCallback">
<pre class=func1>
typedef int dTriCallback (dGeomID TriMesh, dGeomID RefObject, int TriangleIndex);
void dGeomTriMeshSetCallback (dGeomID g, dTriCallback *Callback);
dTriCallback* dGeomTriMeshGetCallback (dGeomID g);
</pre><div class=func2>
Optional per triangle callback. Allows the user to say if collision with a
particular triangle is wanted.
If the return value is zero no contact will be generated.
</div><p><a name="func_dTriArrayCallback">
<a name="func_dGeomTriMeshSetArrayCallback">
<a name="func_dGeomTriMeshGetArrayCallback">
<pre class=func1>
typedef void dTriArrayCallback (dGeomID TriMesh, dGeomID RefObject,
                                const int* TriIndices, int TriCount);
void dGeomTriMeshSetArrayCallback (dGeomID g, dTriArrayCallback* ArrayCallback);
dTriArrayCallback *dGeomTriMeshGetArrayCallback (dGeomID g);
</pre><div class=func2>
Optional per geom callback. Allows the user to get the list of all
intersecting triangles in one shot.
</div><p><a name="func_dTriRayCallback">
<a name="func_dGeomTriMeshSetRayCallback">
<a name="func_dGeomTriMeshGetRayCallback">
<pre class=func1>
typedef int dTriRayCallback (dGeomID TriMesh, dGeomID Ray, int TriangleIndex,
                             dReal u, dReal v);
void dGeomTriMeshSetRayCallback (dGeomID g, dTriRayCallback* Callback);
dTriRayCallback *dGeomTriMeshGetRayCallback (dGeomID g);
</pre><div class=func2>
Optional Ray callback. Allows the user to determine if a ray collides with
a triangle based on the barycentric coordinates of an intersection.
The user can for example sample a bitmap to determine if a collision
should occur.
</div><p><a name="func_dCreateTriMesh">
<pre class=func1>
dGeomID dCreateTriMesh (dSpaceID space, dTriMeshDataID Data,
                        dTriCallback *Callback,
                        dTriArrayCallback * ArrayCallback,
                        dTriRayCallback* RayCallback);
</pre><div class=func2>
Constructor. The <span class=arg>Data</span> member defines the vertex data the newly
created triangle mesh will use.
</div><p><a name="func_dGeomTriMeshSetData">
<pre class=func1>
void dGeomTriMeshSetData (dGeomID g, dTriMeshDataID Data);
</pre><div class=func2>
Replaces the current data.
</div><p><a name="func_dGeomTriMeshClearTCCache">
<pre class=func1>
void dGeomTriMeshClearTCCache (dGeomID g);
</pre><div class=func2>
Clears the internal temporal coherence caches.
</div><p><a name="func_dGeomTriMeshGetTriangle">
<pre class=func1>
void dGeomTriMeshGetTriangle (dGeomID g, int Index, dVector3 *v0,
                              dVector3 *v1, dVector3 *v2);
</pre><div class=func2>
Retrieves a triangle in object space. The <span class=arg>v0</span>, <span class=arg>v1</span> and
<span class=arg>v2</span> arguments are optional.
</div><p><a name="func_dGeomTriMeshGetPoint">
<pre class=func1>
void dGeomTriMeshGetPoint (dGeomID g, int Index, dReal u, dReal v,
                           dVector3 Out);
</pre><div class=func2>
Retrieves a position in object space based on the incoming data.
</div><p><a name="func_dGeomTriMeshEnableTC">
<a name="func_dGeomTriMeshIsTCEnabled">
<pre class=func1>
void dGeomTriMeshEnableTC(dGeomID g, int geomClass, int enable);
int dGeomTriMeshIsTCEnabled(dGeomID g, int geomClass);
</pre><div class=func2>
These functions can be used to enable/disable the use of temporal coherence
during tri-mesh collision checks. Temporal coherence can be enabled/disabled
per tri-mesh instance/geom class pair, currently it works for spheres and
boxes.  The default for spheres and boxes is 'false'.<p>The 'enable' param should be 1 for true, 0 for false.<p>Temporal coherence is optional because allowing it can cause subtle
efficiency problems in situations where a tri-mesh may collide with many
different geoms during its lifespan.  If you enable temporal coherence on
a tri-mesh then these problems can be eased by intermittently calling
 <a class=func href="#func_dGeomTriMeshClearTCCache">dGeomTriMeshClearTCCache</a> for it.
</div><h3 class=section3><a name="sec_10_7_7">10.7.7. Geometry Transform Class</a></h3>A geometry transform `T' is a geom that encapsulates another geom `E',
allowing E to be positioned and rotated arbitrarily with respect to its
point of reference.<p>Most placeable geoms (like the sphere and box) have their point of reference
corresponding to their center of mass, allowing them to be easily connected
to dynamics objects.
Transform objects give you more flexibility - for example, you can
offset the center of a sphere, or rotate a cylinder so that its axis
is something other than the default.<p>T mimics the object E that it encapsulates: T is inserted into a
space and attached to a body as though it was E.
E itself must <i>not</i> be inserted into a space or attached to a body.
E's position and rotation are set to constant values that say how it
is transformed <i>relative</i> to T.
If E's position and rotation are left at their default values, T will
behave exactly like E would have if you had used it directly.<p><a name="func_dCreateGeomTransform">
<pre class=func1>
dGeomID dCreateGeomTransform (dSpaceID space);
</pre><div class=func2>
Create a new geometry transform object, and return its ID.
If <span class=arg>space</span> is nonzero, insert it into that space.
On creation the encapsulated geometry is set to 0.
</div><p><a name="func_dGeomTransformSetGeom">
<pre class=func1>
void dGeomTransformSetGeom (dGeomID g, dGeomID obj);
</pre><div class=func2>
Set the geom that the geometry transform <span class=arg>g</span> encapsulates.
The object <span class=arg>obj</span> must not be inserted into any space, and must not be
associated with any body.<p>If <span class=arg>g</span> has its clean-up mode turned on, and it already encapsulates
an object, the old object will be destroyed before it is replaced with the
new one.
</div><p><a name="func_dGeomTransformGetGeom">
<pre class=func1>
dGeomID dGeomTransformGetGeom (dGeomID g);
</pre><div class=func2>
Get the geom that the geometry transform <span class=arg>g</span> encapsulates.
</div><p><a name="func_dGeomTransformSetCleanup">
<a name="func_dGeomTransformGetCleanup">
<pre class=func1>
void dGeomTransformSetCleanup (dGeomID g, int mode);
int dGeomTransformGetCleanup (dGeomID g);
</pre><div class=func2>
Set and get the clean-up mode of geometry transform <span class=arg>g</span>.
If the clean-up mode is 1, then the encapsulated object will be destroyed
when the geometry transform is destroyed.
If the clean-up mode is 0 this does not happen.
The default clean-up mode is 0.
</div><p><a name="func_dGeomTransformSetInfo">
<a name="func_dGeomTransformGetInfo">
<pre class=func1>
void dGeomTransformSetInfo (dGeomID g, int mode);
int dGeomTransformGetInfo (dGeomID g);
</pre><div class=func2>
Set and get the "information" mode of geometry transform <span class=arg>g</span>.
The mode can be 0 or 1. The default mode is 0.<p>With mode 0, when a transform object is collided with another object
(using <span class=c>dCollide (tx_geom,other_geom,...)</span>), the <span class=c>g1</span> field of the
<span class=c>dContactGeom</span> structure is set to the geom that is
<i>encapsulated</i> by the transform object. This value of <span class=c>g1</span> allows
the caller to interrogate the type of the geom that is transformed,
but it does not allow the caller to determine the position in global
coordinates or the associated body, as both of these properties are used
differently for encapsulated geoms.<p>With mode 1, the <span class=c>g1</span> field of the <span class=c>dContactGeom</span> structure is set
to the transform object itself.
This makes the object appear just like any other kind of geom,
as <a class=func href="#func_dGeomGetBody">dGeomGetBody</a> will return the attached body,
and <a class=func href="#func_dGeomGetPosition">dGeomGetPosition</a> will return the global position.
To get the actual type of the encapsulated geom in this case,
<a class=func href="#func_dGeomTransformGetGeom">dGeomTransformGetGeom</a> must be used.
</div><h2 class=section2><a name="sec_10_8_0">10.8. User defined classes</a></h2>ODE's geometry classes are implemented internally as C++ classes.
If you want to define your own geometry classes you can do this in two ways:
<ol>
<li>	Use the C functions in this section. This has the advantage of
	providing a clean separation between your code and ODE.
<li>	Add the classes directly to ODE's source code. This has the
	advantage that you can use C++ so the implementation will
	potentially be a bit cleaner. This is also the preferred method
	if your collision class is generally useful and you want to
	contribute it to the public source base.
</ol>
What follows is the C API for user defined geometry classes.<p>Every user defined geometry class has a unique integer number.
A new geometry class (call it `X') must provide the following to ODE:
<ol>
<li>	Functions that will handle collision detection and contact generation
	between X and one or more other classes.
	These functions must be of type <span class=c>dColliderFn</span>, which is defined as
	<pre class=code>
typedef int dColliderFn (dGeomID o1, dGeomID o2, int flags,
                         dContactGeom *contact, int skip);</pre>
	This has exactly the same interface as <a class=func href="#func_dCollide">dCollide</a>.
	Each function will handle a specific collision case, where <span class=arg>o1</span>
	has type X and <span class=arg>o2</span> has some other known type.<p><li>	A "selector" function, of type <span class=c>dGetColliderFnFn</span>, which is
	defined as
	<pre class=code>
typedef dColliderFn * dGetColliderFnFn (int num);</pre>
	This function takes a class number (<span class=arg>num</span>), and returns the
	collider function that can handle colliding X with class <span class=arg>num</span>.
	It should return 0 if X does not know how to collide with class
	<span class=arg>num</span>.
	Note that if classes X and Y are to collide, only <i>one</i> needs
	to provide a function to collide with the other.<p>This function is called infrequently - the return values are cached
	and reused.<p><li>	A function that will compute the axis aligned bounding box (AABB) of
	instances of this class.
	This function must be of type <span class=c>dGetAABBFn</span>, which is defined as
	<pre class=code>
typedef void dGetAABBFn (dGeomID g, dReal aabb[6]);</pre>
	This function is given <span class=arg>g</span>, which has type X, and returns the
	axis-aligned bounding box for <span class=arg>g</span>.
	The <span class=arg>aabb</span> array has elements
	(<i>minx</i>, <i>maxx</i>, <i>miny</i>, <i>maxy</i>, <i>minz</i>, <i>maxz</i>).
	If you don't want to compute tight bounds for the AABB, you can just
	supply a pointer to <a class=func href="#func_dInfiniteAABB">dInfiniteAABB</a>, which returns +/- infinity
	in each direction.<p><li>	The number of bytes of "class data" that instances of this class
	need. For example a sphere stores its radius in the class data area,
	and a box stores its side lengths there.
</ol>
The following things are optional for a geometry class:
<ol>
<li>	A function that will destroy the class data. Most classes will not
	need this function, but some will want to deallocate heap memory
	or release other resources.
	This function must be of type <span class=c>dGeomDtorFn</span>, which is defined as
	<pre class=code>
typedef void dGeomDtorFn (dGeomID o);</pre>
	The argument <span class=arg>o</span> has type X.<p><li>	A function that will test whether a given AABB intersects with an
	instance of X.
	This is used as an early-exit test in the space collision functions.
	This function must be of type <span class=c>dAABBTestFn</span>, which is defined as
	<pre class=code>
typedef int dAABBTestFn (dGeomID o1, dGeomID o2, dReal aabb2[6]);</pre>
	The argument <span class=arg>o1</span> has type X.
	If this function is provided it is called by <a class=func href="#func_dSpaceCollide">dSpaceCollide</a>
	when <span class=arg>o1</span> intersects geom <span class=arg>o2</span>, which has an
	AABB given by <span class=arg>aabb2</span>.
	It returns 1 if <span class=arg>aabb2</span> intersects <span class=arg>o1</span>, or 0 if it does not.<p>This is useful, for example, for large terrains.
	Terrains typically have very large AABBs, which are not very useful to
	test intersections with other objects.
	This function can test another object's AABB against the terrain
	without going to the computational trouble of calling the specific
	collision function.
	This has an especially big savings when testing against GeomGroup
	objects.
</ol><p>Here are the functions used to manage custom classes:<p><a name="func_dCreateGeomClass">
<pre class=func1>
int dCreateGeomClass (const dGeomClass *classptr);
</pre><div class=func2>
Register a new geometry class, defined by <span class=arg>classptr</span>.
The number of the new class is returned.
The convention used in ODE is to assign the class number to a global variable
with the name <span class=c>dXxxClass</span> where Xxx is the class name
(e.g. <span class=c>dSphereClass</span>).<p>Here is the definition of the <span class=c>dGeomClass</span> structure:
<pre class=code>
struct dGeomClass {
  int bytes;                  // bytes of custom data needed
  dGetColliderFnFn *collider; // collider function
  dGetAABBFn *aabb;           // bounding box function
  dAABBTestFn *aabb_test;     // aabb tester, can be 0 for none
  dGeomDtorFn *dtor;          // destructor, can be 0 for none
};</pre>
</div><p><a name="func_dGeomGetClassData">
<pre class=func1>
void * dGeomGetClassData (dGeomID);
</pre><div class=func2>
Given a geom, return a pointer to the class's custom data
(this will be a block of the required number of bytes).
</div><p><a name="func_dCreateGeom">
<pre class=func1>
dGeomID dCreateGeom (int classnum);
</pre><div class=func2>
Create a geom of the given class number.
The custom data block will initially be set to 0.
This object can be added to a space using <a class=func href="#func_dSpaceAdd">dSpaceAdd</a>.
</div><p>When you implement a new class you will usually write a function that does
the following:
<ol>
<li>	If the class has not yet been created, create it.
	You should be careful to only ever create the class once.
<li>	Call <a class=func href="#func_dCreateGeom">dCreateGeom</a> to make an instance of the class.
<li>	Set up the custom data area.
</ol><h2 class=section2><a name="sec_10_9_0">10.9. Composite objects</a></h2>Consider the following objects: <ul>
<li>	A table that is made out of a box for the top and a box for each leg.
<li>	A branch of a tree that is modeled from several cylinders
	joined together.
<li>	A molecule that has spheres representing each atom.
</ul>
If these objects are meant to be <i>rigid</i> then it is necessary to use
a single rigid body to represent each of them.
But it might seem that performing collision detection is a problem,
because there is no single geometry class that can represent a
complex shape like a table or a molecule.
The solution is to use a <i>composite</i> collision object that is a
combination of several geoms.<p>No extra functions are needed to manage composite objects: simply
create each component geom and attach it to the same body. To move
and rotate the separate geoms with respect to each other in the same
object, geometry transforms can be used to encapsulate them. That's
all there is to it!<p>However there is one <i>caveat</i>: You should never create a composite
object that will result in collision points being generated very close
together.
For example, consider a table that is made up of a box for the top and four
boxes for the legs.
If the legs are flush with the top, and the table is lying on the ground on
its side, then the contact points generated for the boxes may coincide
where the legs join to the top.
ODE does not currently optimize away coincident contact points, so this
situation can lead to numerical errors and strange behavior.<p>In this example the table geometry should be adjusted so that the legs are
not flush with the sides, making it much more unlikely that coincident
contact points will be generated.
In general, avoid having different contact surfaces that overlap,
or that line up along their edges.<h2 class=section2><a name="sec_10_10_0">10.10. Utility functions</a></h2><a name="func_dClosestLineSegmentPoints">
<pre class=func1>
void dClosestLineSegmentPoints (const dVector3 a1, const dVector3 a2,
				const dVector3 b1, const dVector3 b2,
				dVector3 cp1, dVector3 cp2);
</pre><div class=func2>
Given two line segments A and B with endpoints <span class=arg>a1</span>-<span class=arg>a2</span> and
<span class=arg>b1</span>-<span class=arg>b2</span>, return the points on A and B that are closest to each
other (in <span class=arg>cp1</span> and <span class=arg>cp2</span>).
In the case of parallel lines where there are multiple solutions, a solution
involving the endpoint of at least one line will be returned.
This will work correctly for zero length lines, e.g. if <span class=arg>a1</span>==<span class=arg>a2</span>
and/or <span class=arg>b1</span>==<span class=arg>b2</span>.
</div><p><a name="func_dBoxTouchesBox">
<pre class=func1>
int dBoxTouchesBox (const dVector3 _p1, const dMatrix3 R1,
                    const dVector3 side1, const dVector3 _p2,
                    const dMatrix3 R2, const dVector3 side2);
</pre><div class=func2>
Given boxes (<span class=arg>p1</span>,<span class=arg>R1</span>,<span class=arg>side1</span>) and
(<span class=arg>p2</span>,<span class=arg>R2</span>,<span class=arg>side2</span>), return 1 if they intersect or 0 if not.
<span class=arg>p</span> is the center of the box, <span class=arg>R</span> is the rotation matrix for
the box, and <span class=arg>side</span> is a vector of x/y/z side lengths.
</div><p><a name="func_dInfiniteAABB">
<pre class=func1>
void dInfiniteAABB (dGeomID geom, dReal aabb[6]);
</pre><div class=func2>
This function can be used as the AABB-getting function in a geometry class,
if you don't want to compute tight bounds for the AABB.
It returns +/- infinity in each direction.
</div><h2 class=section2><a name="sec_10_11_0">10.11. Implementation notes</a></h2><h3 class=section3><a name="sec_10_11_1">10.11.1. Large Environments</a></h3>Often the collision world will contain many objects that are part of
the static environment, that are not associated with rigid bodies.
ODE's collision detection is optimized to detect geoms that do not
move and to precompute as much information as possible about these
objects to save time.  For example, bounding boxes and internal
collision data structures are precomputed.<h3 class=section3><a name="sec_10_11_2">10.11.2. Using a Different Collision Library</a></h3>Using ODE's collision detection is optional - an alternative collision
library can be used as long as it can supply <span class=c>dContactGeom</span> structures
to initialize contact joints.<p>The dynamics core of ODE is mostly independent of the collision library
that is used, except for four points:
<ol>
<li>	The <span class=c>dGeomID</span> type must be defined, as each body can store a
	pointer to the first geometry object that it is associated with.<p><li>	The <span class=c>dGeomMoved()</span> function must be defined, with the following
	prototype:<p><pre class=code>void dGeomMoved (dGeomID);</pre><p>This function is called by the dynamics code whenever a body moves:
	it indicates that the geometry object associated with the body is
	now in a new position.<p><li>	The <span class=c>dGeomGetBodyNext()</span> function must be defined, with the following
	prototype:<p><pre class=code>dGeomID dGeomGetBodyNext (dGeomID);</pre><p>This function is called by the dynamics code to traverse the list of
	geoms that are associated with each body. Given a geom attached to
	a body, it returns the next geom attached to that body, or 0 if there
	are no more geoms.<p><li>	The <span class=c>dGeomSetBody()</span> function must be defined, with the following
	prototype:<p><pre class=code>void dGeomSetBody (dGeomID, dBodyID);</pre><p>This function is called in the body destructor code (with the second
	argument set to 0) to remove all references from the geom to the body.
</ol>
If you want an alternative collision library to get body-movement
notifications from ODE, you should define these types and functions
appropriately.<h1 class=section1><a name="sec_11_0_0">11. How To Make Good Simulations</a></h1>[just notes for now]<h2 class=section2><a name="sec_11_1_0">11.1. Integrator accuracy and stability</a></h2><ul>
<li>	integrator will not give exact solution
<li>	what is stabilty
<li>	integrator types (exp &amp; imp, order)
<li>	tradeoff between accuracy, stability and work
</ul><h2 class=section2><a name="sec_11_2_0">11.2. Behavior may depend on step size</a></h2><ul>
<li>	smaller step = more accurate, more stable
<li>	10*0.1 not the same as 5*0.2
<li>	tweak at final frame rate
</ul><h2 class=section2><a name="sec_11_3_0">11.3. Making things go faster</a></h2>What factors does execution speed depend on?
Each joint removes a number of degrees of freedom (DOFs) from the system.
For example the ball and socket removes three, and the hinge removes five.
For each separate group of bodies connected by joints, where:
<ul>
<li>	<i>m</i><sub>1</sub> is the number of joints in the group,
<li>	<i>m</i><sub>2</sub> is the total number of DOFs removed by those joints, and
<li>	<i>n</i> is the number of bodies in the group,
</ul>
then the computing time per step for the group is proportional to:
	<div class=math><i>k</i><sub>1</sub> <i>O</i>(<i>m</i><sub>1</sub>) + <i>k</i><sub>2</sub> <i>O</i>(<i>m</i><sub>2</sub><sup>3</sup>) + <i>k</i><sub>2</sub> <i>O</i>(<i>n</i>)</div><p>ODE currently relies on factorization of a ``system'' matrix that has one
row/column for each DOF removed (this is where the <i>O</i>(<i>m</i><sub>2</sub><sup>3</sup>)
comes from).
In a 10 body chain that uses ball and socket joints, roughly 30-40% of the
time is spent filling in this matrix, and 30-40% of the time is spent
factorizing it.<p>Thus, to speed up your simulation you might consider:
<ul>
<li>	Using less joints - often small bodies and their associated joints
	can be replaced by purely kinematic ``fakes'' without harming
	physical realism.
<li>	Replacing multiple joints with simpler alternatives.
	This will become easier as more specialized joint types are defined.
<li>	Using less contacts.
<li>	Preferring frictionless or viscous friction contacts (that remove one
	DOF) over Coulomb friction contacts (that remove three DOFs)
	where possible.
</ul>
In the future ODE will implement techniques that scale better with the number
of joints.<h2 class=section2><a name="sec_11_4_0">11.4. Making things stable</a></h2><ul>
<li>	stiff springs / stiff forces are bad.
<li>	hard constraints are good.
<li>	dependence on integration timestep.
<li>	Use powered joint, joint limits, built-in springs as much as possible,
	avoid explicit forces.
<li>	mass ratios - e.g. a whip. Joints that connect large and small masses
	together will have a harder time keeping their error low.
<li>	if bodies move faster than is reasonable for the timestep
<li>	inertias with long axes
</ul><p>Increasing the global CFM will make the system more numerically robust and
less susceptible to stability problems.
It will also make the system look more ``spongy'', so a tradeoff has to be
found.<p>Redundant constraints (two or more constraints that ``try and do the same
job'') will fight each other and cause stability problems.
The numerical cause of this problem is singularity in the system matrix.
One example of this is if two contacts joints connect the same pair of
bodies at the same point.
Another example is if a virtual hinge joint is created between two bodies
by connecting them with two ball joints, spaced apart along the hinge axis
(this is bad because the two ball joints try to remove six degrees of freedom
from the system, but a real hinge joint would only remove five).<p>Redundant constraints fight each other and generate strange forces in the
system that can swamp the normal forces.
For example, an affected body might fly around as though it has a life
of its own, with complete disregard for gravity.<h2 class=section2><a name="sec_11_5_0">11.5. Using constraint force mixing (CFM)</a></h2><ul>
<li>	allow singular configurations
<li>	effects: jitter or strange forces due to error amplification,
	LCP solver may go slow
<li>	allow compliant joints (this may be unwanted also)
</ul><h2 class=section2><a name="sec_11_6_0">11.6. Avoiding singularities</a></h2><ul>
<li>	Singularity occurs when there are more joints than needed to constrain
	the bodies motions.
<li>	Multiple (incompatible) joints between bodies, esp joint + contact
	(don't collide objects that are joined together).
<li>	increasing CFM
<li>	unintentional - box chain on floor, other assemblies
<li>	use minimum joints for correct behavior. use correct joints for desired
	behavior
<li>	adding global CFM usually helps
</ul><h2 class=section2><a name="sec_11_7_0">11.7. Other stuff</a></h2><ul>
<li>	contact jitter when pushed out too far - soln: use softness
<li>	keep lengths and masses around 1
<li>	LCP solver takes a variable number of iterations (only
	non-deterministic part). if it takes too long, increase global
	CFM, prevent multiple contacts (or similar), and limit high
	ratio of force magnitudes (tree grabbing problem)
<li>	hinge limits outside +/- pi
</ul><h1 class=section1><a name="sec_12_0_0">12. FAQ</a></h1>This chapter has some common questions and their answers.
For further information, you can check out the
<a href="http://q12.org/cgi-bin/wiki.pl?ODE_Wiki_Area">ODE Wiki</a>,
a community-supported website.<h2 class=section2><a name="sec_12_1_0">12.1. How do I connect a body to the static environment with a joint?</a></h2>Use <a class=func href="#func_dJointAttach">dJointAttach</a> with arguments <span class=c>(body,0)</span> or <span class=c>(0,body)</span>.<h2 class=section2><a name="sec_12_2_0">12.2. Does ODE need or use graphics library X ?</a></h2>No. ODE is a computational engine, and is completely independent
of any graphics library.
However the examples that come with ODE use OpenGL,
and most interesting uses of ODE will need some graphics library to
make the simulation visible to the user.
But that's your problem.<h2 class=section2><a name="sec_12_3_0">12.3. Why do my rigid bodies bounce or penetrate on collision?
My restitution is zero!</a></h2>Sometimes when rigid bodies collide without restitution, they appear to
inter-penetrate slightly and then get pushed apart so that they only just
touch.
The problem gets worse as the time step gets larger.
What is going on?<p>The contact joint constraint is only applied after the collision is detected.
If a fixed time step is being used, it is likely that the bodies have
already penetrated when this happens.
The error reduction mechanism will push the bodies apart, but this can
take a few time steps (depending on the value of the ERP parameter).<p>This penetration and pushing apart sometimes makes the bodies look like they
are bouncing, although it is completely independent of whether restitution
is on or not.<p>Some other simulators have individual rigid bodies take variable sized
timesteps to make sure bodies never penetrate much.
However ODE takes fixed size steps, as automatically choosing a
non-penetrating step size is problematic for an articulated rigid body
simulator (the entire ARB structure must be stepped to account for the
first penetration, which may result in very small steps).<p>There are three fixes for this problem:
<ul>
<li>	Take smaller time steps.
<li>	Increase ERP to make the problem less visible.
<li>	Do your own variable sized time stepping somehow.
</ul><h2 class=section2><a name="sec_12_4_0">12.4. How can an immovable body be created?</a></h2>In other words, how can you create a body that doesn't move, but that
interacts with other bodies?
The answer is to create a geom only, without the corresponding
rigid body object.
The geom is associated with a rigid body ID of zero.
Then in the contact callback when you detect a collision between two geoms
with a nonzero body ID and a zero body ID, you can simply pass those
two IDs to the <a class=func href="#func_dJointAttach">dJointAttach</a> function as normal.
This will create a contact between the rigid body and the static environment.<p>Don't try to get the same effect by setting a very high mass/inertia on the
``motionless'' body and then resetting it's position/orientation on each
time step.
This can cause unexpected simulation errors.<h2 class=section2><a name="sec_12_5_0">12.5. Why would you ever want to set ERP less than one?</a></h2>From the definition of the ERP value, it seems than setting it to one is the
best approach, because then all joint errors will be fully corrected at
each time step.
However, ODE uses various approximations in its integrator, so ERP=1 will not
usually fix 100% of the joint error.
ERP=1 can work in some cases, but it can also result in instability in some
systems.
In these cases you have the option of reducing ERP to get a better behaving
system.<h2 class=section2><a name="sec_12_6_0">12.6. Is it advisable to set body velocities directly, instead of
applying a force or torque?</a></h2>You should only set body velocities directly if you are setting the system
to some initial configuration.
If you are setting body velocities every time step (for example from motion
capture data) then you are probably abusing your physical model, i.e. forcing
the system to do what you want rather than letting it happen naturally.<p>The preferred method of setting body velocities during the simulation is to
use joint motors.
They can set body velocities to a desired value in one time step, provided
that the force/torque limit is high enough.<h2 class=section2><a name="sec_12_7_0">12.7. Why, when I set a body's velocity directly, does it come up to speed
slower when joined to other bodies?</a></h2>What is likely happening is that you are setting the velocity of one
body without also setting the velocity of the bodies that it is joined to.
When you do this, you cause error in the system in subsequent time steps
as the bodies come apart at their joints.
The error reduction mechanism will eventually correct for this and pull the
other bodies along, but it may take a few time steps and it will cause a
noticeable "drag" on the original body.<p>Setting the velocity of a body will affect that body alone.
If it is joined to other bodies, you must set the velocity of each one
separately (and correctly) to prevent this behavior.<h2 class=section2><a name="sec_12_8_0">12.8. Should I scale my units to be around 1.0 ?</a></h2>Say you need to simulate some behavior on the scale of a few millimeters
and a few grams.
These small lengths and masses will usually work in ODE with no problem.
However occasionally you may experience stability problems that are caused
by lack of precision in the factorizer.
If this is the case, you can try scaling the lengths and masses in your
system to be around 0.1..10.
The time step should also be be scaled accordingly.
The same guideline applies when large lengths and masses are being used.<p>In general, length and mass values around 0.1..1.0 are better as the
factorizer may not lose so much precision.
This guideline is especially helpful when single precision is being used.<h2 class=section2><a name="sec_12_9_0">12.9. I've made a car, but the wheels don't stay on properly!</a></h2>If you are building a car simulation, typically you create a chassis body
and attach four wheel bodies. However, you may discover that when you drive
it around the wheels rotate in incorrect directions, as though the joint
was somehow becoming ineffective.
The problem is observed when the car is moving fast (so the wheels are
rotating fast), and the car tries to turn a corner.
The wheels appear to rotate off their proper constraints as though the
``axles'' had become bent.
If the wheels are rotating slowly, or the turn is made slowly, the problem
is less apparent.<p>The problem is that numerical errors are being caused by the high rotation
speed of the wheels.
Two functions are provided to fix this problem:
<a class=func href="#func_dBodySetFiniteRotationMode">dBodySetFiniteRotationMode</a> and <a class=func href="#func_dBodySetFiniteRotationAxis">dBodySetFiniteRotationAxis</a>.
The wheel bodies should have their finite rotation mode set, and the
wheel's finite rotation axes should be set every time step to match their
hinge axes.
This will hopefully fix most of the problem.<h2 class=section2><a name="sec_12_10_0">12.10. How do I make ``one way'' collision interaction</a></h2>Suppose you need to have two bodies (A and B) collide.
The motion of A should affect the motion of B as usual, but B
should not influence A at all.
This might be necessary, for example, if B is a physically simulated camera
in a VR environment.
The camera needs collision response so that it doesn't enter into any scene
objects by mistake, but the motion of the camera should not affect the
simulation.
How can this be achieved?<p>Here is a good solution: when the collision is detected, don't create a
contact joint between A and B as you normally would.
Instead, attach the contact joint between B and 0 (the static environment).
That way the body A will appear to B as though it is static and unmovable.
This approach may result in some penetration between A and B, but
this will not be a problem in many applications.<h2 class=section2><a name="sec_12_11_0">12.11. The Windows version of ODE crashes with large systems</a></h2>ODE with <a class=func href="#func_dWorldStep">dWorldStep</a> requires stack space roughly on the order of <i>O</i>(<i>n</i>)+<i>O</i>(<i>m</i><sup>2</sup>),
where <i>n</i> is the number of bodies and <i>m</i> is the sum of all the joint
constraint dimensions.
If <i>m</i> is large, this can be a lot of space!<p>Unix-like operating systems typically allocate stack space as it is needed,
with an upper limit that might be in the hundreds of Mb.
Windows compilers normally allocate a much smaller stack.
If you experience crashes when running large systems, try increasing the
stack size.
For example, the MS VC++ command line compiler accepts the <span class=c>/Stack:num</span>
flag to set the upper limit.<p>Another option is to switch to <a class=func href="#func_dWorldQuickStep">dWorldQuickStep</a>.<h2 class=section2><a name="sec_12_12_0">12.12. My simple rotating bodies are unstable!</a></h2>If you have a box whose sides have different lengths, and you start it
rotating in free space, you should observe that it just tumbles at the same
speed forever.
But sometimes in ODE the box will gain speed by itself, spinning faster and
faster until it ``explodes'' (disappears off to infinity).
Here is the explanation:<p>ODE uses a first order semi-implicit integrator.
The ``semi implicit'' means that some forces are calculated as though an
implicit integrator is being used, and other forces are calculated as though
the integrator is explicit.
The constraint forces (applied to bodies to keep the constraints together)
are implicit, and the "external" forces (applied by the user, and due to
rotational effects) are explicit.
Now, inaccuracy in implicit integrators is manifested as a reduction in
energy - in other words the integrator damps the system for you.
Inaccuracy in explicit integrators has the opposite effect - it increases the
system energy.
This is why systems simulated with explicit first order integrators can
explode.<p>So, a single body tumbling in space is effectively explicitly integrated.
If the body's moments of inertia were equal (e.g. if it is a sphere) then the
rotation axis will remain constant, and the integrator error will be small.
If the body's moments of inertia are unequal then the rotation axis wobbles
as momentum is transferred between different rotation directions.
This is the correct physical behavior, but it results in higher integrator
error.
The integrator in this case is explicit so the error increases the energy,
which causes faster and faster rotation, causing more and more error -
leading to the explosion.
The problem is particularly evident with long thin objects, where the 3
moments of inertia are highly unequal.<p>To prevent this, do one or more of the following:
<ul>
<li>	Make sure freely rotating bodies are dynamically symmetric (i.e. all
	moments of inertia are the same - the inertia matrix is a constant
	times the identity matrix).
	Note that you can still render and collide with a long thin box even
	though it has the inertia of a sphere.
<li>	Make sure freely rotating bodies don't spin too fast (e.g. don't
	apply large torques, or supply extra damping forces).
<li>	Add extra damping elements to the environment, e.g. don't use bouncy
	collisions that can reflect energy.
<li>	Use smaller timesteps. This is bad for two reasons: it's slower,
	and ODE currently only has a first order integrator so the added
	accuracy is minimal.
<li>	Use a higher order integrator. This is not yet an option in ODE.
</ul><p>In the future I may add a feature to ODE to modify the rotational dynamics
of selected bodies so that they exhibit no rotational error with ODEs
integrator.<h2 class=section2><a name="sec_12_13_0">12.13. My rolling bodies (e.g. wheels) sometimes get stuck between geoms</a></h2>Consider a system where rolling bodies roll over an environment made
up of multiple geometry objects. For example, this might be a car
driving over a terrain (the rolling bodies are the wheels).
If you find that the rolling bodies mysteriously come to a stop when
they roll from one geometry object to another, or when they receive
multiple contact points, then you may need to use a different contact
friction model. This section explains the problem and the solution.<h3 class=section3><a name="sec_12_13_1">12.13.1. The Problem</a></h3>An example of such a system is shown in figure 13, which
shows a ball that has just rolled down a ramp and touched the ground.<p><center>
	<img border=1 src="pix/rollingcontact.jpg"><br><br>
	<b>Figure 13</b>: A problem with rolling contact.
	</center><p>Normally, the ball should continue rolling along the ground, towards
the right. However, if ODE's default contact friction mode is being used
then the ball will come to a complete stop when it hits the ground.
Why?<p>ODE has two ways to approximate friction: the default way (called the
constant-force-limit approximation, or ``box friction'') and an
improved way (called ``friction pyramid approximation 1'') which is
obtained by setting the <span class=c>dContactApprox1</span> flag in the contact
joint's surface mode field.<p>Consider the above picture. There are two contact points, one between
the ball and the ramp, the other between the ball and the ground.  If
the box friction mode is used in both contacts and the <span class=c>mu</span> parameter
is set to <span class=c>dInfinity</span> then the ball can not slip against the ramp or
ground at either contact.<p>If no slip is possible at a ball contact point, then the center of the
ball <i>must</i> move along a path that is an arc around the contact
point. Thus the center of the ball is required to simultaneously move
along the path ``Arc 1'' and ``Arc 2''. The only way to satisfy both
paths at once is for the ball to stop moving altogether.<p>This is not a bug in ODE - so what is going on here? Objects in real
life do not get stuck like this. The problem is that, in the simple
``box'' approximation of friction the tangential force available at a
contact constraint to stop it slipping is <i>independent</i> of the
normal force that prevents penetration. This is not real-life physics,
so we should not be surprised that non-real-life motion results.<p>Note that this problem does not occur if <span class=c>mu</span> is set to zero,
but this is not a helpful solution because we need some amount of
friction to model the real world.<h3 class=section3><a name="sec_12_13_2">12.13.2. The Solution</a></h3>The solution is to use the <span class=c>dContactApprox1</span> flag in the contact's
surface mode field, and set <span class=c>mu</span> to some appropriate value between 0
and infinity. This mode ensures that there will only be a tangential
anti-slipping force at the contact point if the contact normal force
is nonzero. In the above example it turns out that contact-1 will have
a zero normal force, so there will be no force applied at contact-1 at
all, and the problem is solved! (the ball will roll along the ground
properly.)<p>The <span class=c>dContactApprox1</span> mode may not be appropriate in all situations,
which is why it is optional. It is important to remember that,
although it is a better friction approximation, it is not true Coulomb
friction. Thus it is still possible that you may encounter some
examples of non-physical behavior.<h1 class=section1><a name="sec_13_0_0">13. Known Issues</a></h1><ul>
<li>	When assigning a mass to a rigid body, the center of mass must be
	(0,0,0) relative to the body's position.
	But in fact this limitation has been in ODE from the start, so
	we can now regard it as a ``feature'' :)
</ul><h1 class=section1><a name="sec_14_0_0">14. ODE Internals</a></h1>[only notes for now]<p><ul><p><li>	Internally, all 6x1 spatial velocities and accelerations are split
	into 3x1 position and angular components, which are stored as
	contiguous 4x1 vectors.<p><li>	Lagrange multiplier velocity based model due to Trinkle and Stewart.
<li>	Friction due to Baraff.<p><li>	Stability over accuracy.<p><li>	Talk about the different methods possible.
	Say how realtime constraints make the problem much more difficult.<p><li>	Factorizer.<p><li>	LCP solver.<p><li>	Equations of motion.<p><li>	Friction model and approximations.
</ul><p>Why don't I implement a proper friction pyramid or friction cone
(e.g. Baraff's version) ?
	Because I have to factor non-symmetric (and possibly indefinite)
	matrices, for either static or dynamic friction.
	Speed was considered more important - the current friction
	approximation only needs a symmetric factorization, which is twice
	as fast.<h2 class=section2><a name="sec_14_1_0">14.1. Matrix storage conventions</a></h2>Matrix operations like factorization are expensive, so we must store the data
in a way that is most useful to the matrix code.
I want to do 4-way SIMD optimizations later, so the format is this: store
the matrix by rows, and each row is rounded up to a multiple of 4 elements.
The extra "padding" elements at the end of each row/column must be set
to 0.
This is called the "standard format".
Hopefully this decision will remain good in the future, as more and
more processors have 4-way SIMD (especially for fast 3D graphics).<p>The exception: matrices that have only one column or row (vectors), are always
stored as consecutive elements in standard row format, i.e. there is no
interior padding, only padding at the end.<p>Thus: all 3x1 floating point vectors are stored as 4x1 vectors: (x,x,x,0).<h2 class=section2><a name="sec_14_2_0">14.2. Internals FAQ</a></h2><h3 class=section3><a name="sec_14_2_1">14.2.1. Why do some structures have a <span class=c>dx</span> prefix and some have a
<span class=c>d</span> prefix?</a></h3>The <span class=c>dx</span> prefix is used for internal structures that should never be
visible externally.
The <span class=c>d</span> prefix is used for structures that are part of the public
interface.<h3 class=section3><a name="sec_14_2_2">14.2.2. Returned Vectors</a></h3>There seem to be 2 ways of returning vectors in ODE, e.g.:
<pre class=code>
    const dReal* dBodyGetPosition (dxBodyID);
    void dWorldGetGravity (dxWorldID, dVector3);</pre>
Why?
The second way is the 'official' way.
The first way returns pointers to volatile internal data structures and is
less clean API-wise.
For a stable API I feel that filling in vectors is cleaner than returning
pointers to vectors, for two reasons:
<ol>
<li>	The returned vector values may have to be calculated somehow, so
	there is no internal ``cache'' to return a pointer to.
<li>	The internal data structures may be moved, which is a problem if
	the user keeps the returned pointer and uses it later.
</ol>
As it happens these two cases don't currently happen in ODE - most returned
vector data is cached and always at the same address.
But having the freedom to change things in the future is useful.
The current API shouldn't slow you down because the cases where you need to
be fast (i.e. getting body transforms) return pointers anyway - breaking my
own rule.


</body>
</html>

